0

I've been trying to implement an input member function for a Date class.Here's what I have:

class Date {
    int year_;
    int mon_;
    int day_;
    int readErrorCode_;
    int value()const;
    void errCode(int errrorCode);

    public:
         std::istream& read(std::istream& istr);
         std::ostream& write(std::ostream& ostr)const;
}


std::istream& Date::read(std::istream& istr) {
    istr.get(year_,5);
    return istr;
}

I want to extract 4 characters from input and save it in my parameter year_ for my Date class, but I got an error for the istr.get, I wonder why istr.get does not work while cin.get works.

Error message is: no instance of overloaded function "std::basic_istream::get[with _Elem=char, _traits]" matches the argument list argument types are (int,int) object type is: std::istream

Andy Lin
  • 116
  • 1
  • 9
  • We're not going to throw random guesses as to what the error is. Put it [in your question](https://stackoverflow.com/posts/45604173/edit), along with full details of your `Date` class. [`std::istream::get`](http://en.cppreference.com/w/cpp/io/basic_istream/get) supports multiple input forms, so knowing what you're trying to do and what you're trying it *with* is pretty important. Finally, this function invokes undefined behavior. It says it returns a `std::istream&`, but in fact returns nothing. – WhozCraig Aug 10 '17 at 04:01
  • Thanks for the update. The error is clear. There is no [`std::istream::get`](http://en.cppreference.com/w/cpp/io/basic_istream/get) that takes `int` and size as arguments. If this works for `std::cin.get`, I'm pressed to see how, as it has the same offerings (and same restrictions). You seem to want `istr >> date`, but that's just speculation, since it isn't clear whether a binary raw-read, or formatted-read, is desired or intended. – WhozCraig Aug 10 '17 at 04:24
  • Thank you so much for clarifying. My goal is to extract numbers from input in the format YYYY/MM/DD and save numbers in year_ mon_ and day_ respectively, how would I accomplish this using istream member function above? – Andy Lin Aug 10 '17 at 04:44
  • I'd probably use a combination of a delimited overload of [`std::getline`](http://en.cppreference.com/w/cpp/string/basic_string/getline) and [`std::stoi`](http://en.cppreference.com/w/cpp/string/basic_string/stol) to accomplish what you're describing. – WhozCraig Aug 10 '17 at 06:19

1 Answers1

0

If you are willing to use get function you can read char by char like

char c; while (is.get(c)) //concatenate into string if not / delim;

Also there is istream& get (streambuf& sb, char delim); method, which I do not know much about.

However, the easiest way would be to convert istream to std::string then use substring method of std::string. There are examples in How to read entire stream into a std::string?.

Hakes
  • 631
  • 3
  • 13