15

我正在尝试使用 std::getline,但我的编译器告诉我 getline 没有被识别?

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <fstream>
#include <cstdlib>

int main(){
    using namespace std;
    string line;
    ifstream ifile("test.in");
    if(ifile.is_open()){
        while(ifile.good()){
            getline(ifile,line);
        }
    }
}
4

3 回答 3

33

std::getline is defined in the string header.

#include <string>

Also, your code isn't using anything from cstring, cstdio, cmath, or cstdlib; why bother including these?

EDIT: To clarify the confusion regarding the cstring and string headers, cstring pulls the contents of the C runtime library's string.h into the std namespace; string is part of the C++ standard library and contains getline, std::basic_string<> (and its specializations std::string and std::wstring), etc. -- two very different headers.

于 2011-04-25T17:35:21.383 回答
3

正如 ildjarn 指出的那样,该函数是在中声明的<string>,我很惊讶您在以下位置没有收到错误:

string line;

另外,这个:

 while(ifile.good()){
      getline(ifile,line);
 }

不是编写读取循环的方法。您必须测试读取操作是否成功,而不是当前流状态。你要:

while( getline(ifile,line) ) {
}
于 2011-04-25T17:39:58.523 回答
0

发生这种情况是因为 getline 来自字符串库,您需要#include <string>#include <cstring>

于 2020-05-15T00:19:13.270 回答