【问题标题】:c++ reading from either an ifstream or stringstream with same loopc++ 从具有相同循环的 ifstream 或 stringstream 中读取
【发布时间】:2015-09-22 23:39:20
【问题描述】:

我有一个函数需要从 ifstream(磁盘文件中的文本)或 stringstream(内存中的文本)中读取。

这是我想做的一个例子:

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

需要说它不会编译。任何人都可以提出一个适当的方法来实现这一点吗?

【问题讨论】:

  • 不要使用file == true。如果file 已经是true,它给你true,如果filefalse,它给你假,所以没有理由这样做,永远。实际上,由于这是 C++,所以file == true 可能会为某些应该被视为正确的值提供错误的结果。
  • 你是说我应该用它来测试布尔值:if(file)
  • 是的。它更简洁,更好的编码风格。 ==!=< 等比较操作都会产生一个布尔值,所以如果你已经有了一个布尔值,就不需要使用比较运算符来获得一个。

标签: c++


【解决方案1】:

所有 iostreams 类都派生自公共基类。输入流均源自istream,输出流均源自ostream。大多数需要处理输入流或输出流(但并不真正关心它是否来自文件、字符串等)的典型函数只处理对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);
}

【讨论】:

  • 我还是一头雾水。 getline(ss, oneline) 工作正常,而 getline(inFile, oneline) 工作正常,但 getline((file)?inFile:ss, oneline)) 失败并出现错误:没有匹配函数调用 'getline(void*, std ::string&)' 我可以用演员表解决这个问题吗?
猜你喜欢
  • 1970-01-01
  • 2013-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-20
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多