简体   繁体   中英

how to use get() in input member function

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

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? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM