简体   繁体   中英

c++ reading from either an ifstream or stringstream with same loop

I have a function that either needs to read from an ifstream (text from a file on disk) or a stringstream (text in memory).

This is an example of what I want to do:

void myFunction(bool file,stringstream& ss){
   ifstream inFile;
   string oneline;
   if (file == true){
    //code to open file with inFile
   }
   while (getline(file==true?inFile:ss, oneline)){
   // ..process lines
   }
   ...
   ...

Needles to say it won't compile. Can anyone suggest a proper way to achieve this?

All the iostreams classes derive from common base classes. The input streams all derive from istream and the output streams all derive from ostream . Most typical functions that need to deal with an input stream or output stream (but don't really care whether it's from a file, string, etc.) just deal with a reference to an istream or ostream , something like this:

void myFunction(std::istream &is) {
    std::string oneline;
    while (getline(is, oneline))
       process(oneline);
}

if (file) {
    std::ifstream inFile(filename);
    myFunction(inFile);
}
else {
    std::istringstream fromMemory(...);
    myFunction(fromMemory);
}

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