Getline问题与输入打开文件流

时间:2013-04-28 15:03:53

标签: c++ string getline

我正在试图弄清楚为什么现在已经破了,因为我有它工作,我不确定是什么问题。我正在尝试从已打开的文件中获取一个简单的getline,然而,编译器一直给我错误。我已经尝试过找到这些问题的其他人,但我还是找不到其他人。有什么建议吗?

void Foo::bar(ifstream &inputFile)
{
// Read in the data, parse it out, and 
// call loadQueue
string input;
do {    
    getline(inputFile, input);
    loadQueue(input);
}while (!(inputFile.eof()));

}

以下是我得到的回报:

g++    -c -o Airworthy.o Airworthy.cpp
Foo.cpp: In member function ‘void Airworthy::readData(std::ifstream&)’:
Foo.cpp:25:27: error: no matching function for call to ‘getline(std::ifstream&, std::string&)’
Foo.cpp:25:27: note: candidates are:
In file included from /usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.2/../../../../include/c++/4.7.2/string:55:0,
             from /usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.2/../../../../include/c++/4.7.2/bits/locale_classes.h:42,
             from /usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.2/../../../../include/c++/4.7.2/bits/ios_base.h:43,
             from /usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.2/../../../../include/c++/4.7.2/ios:43,
             from /usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.2/../../../../include/c++/4.7.2/ostream:40,
             from /usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.2/../../../../include/c++/4.7.2/iostream:40,

关于问题的任何想法?

2 个答案:

答案 0 :(得分:4)

您很可能忘记#include所有必需的标准标题。一种可能性是:

#include <fstream>

或许你忘了:

#include <string> 

您必须明确地#include所有相关的标准标题,而不依赖于通过其他标题的间接包含。

答案 1 :(得分:1)

正如安迪所说,你需要适当的包括。有, 但是,您的代码至少还有两个主要问题(一个 其中会影响你需要的东西):

  • 你永远不应该(或几乎从不)传递ifstream作为 函数的参数。除非功能要做 openclose,您应该将其std::istream&传递给istream 它可以使用任何ifstream调用,而不仅仅是<istream>

    更改此内容后,您需要添加<fstream>和 不是<fstream>。 (<istream>包括! inputFile.eof()。还有很多 更多你不需要的东西。)

  • 你永远不应该在while ( std::getline( inputFile, input ) ) {4 // ... } 上循环。它没有 工作。在你的情况下,循环应该是

    do...while

    它有效,几乎没有别的。

    通常,input循环几乎总是错误的 做输入;它会导致您处理输入,即使在 它失败了(你做了 - 在{之后}使用getline getline但在测试inputFile.eof()是否成功之前 是一个错误)。而istream::eof()的结果则不然 在输入失败之前确实很好地定义了。运用 控制循环的{{1}}几乎总是错误。

相关问题