简体   繁体   English

c ++从ifstream或stringstream读取相同的循环

[英]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). 我有一个函数需要从ifstream(磁盘上的文件中的文本)或字符串流(内存中的文本)中读取。

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. 所有iostreams类都派生自公共基类。 The input streams all derive from istream and the output streams all derive from ostream . 输入流都来自istream ,输出流都来自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: 需要处理输入流或输出流的大多数典型函数(但不关心它是来自文件,字符串等)只是处理对istreamostream的引用,如下所示:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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