C++ std 没有成员“getline”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5781132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:52:40  来源:igfitidea点击:

std has no member 'getline'?

c++iostdgetline

提问by pighead10

I'm trying to use std::getline, but my compiler is telling me that getline isn't identified?

我正在尝试使用 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);
        }
    }
}

回答by ildjarn

std::getlineis defined in the stringheader.

std::getlinestring头文件中定义。

#include <string>

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

此外,您的代码没有使用cstring, cstdio, cmath, 或 中的任何内容cstdlib;为什么要包括这些?

EDIT:To clarify the confusion regarding the cstringand stringheaders, cstringpulls the contents of the C runtime library'sstring.hinto the stdnamespace; stringis part of the C++ standard libraryand contains getline, std::basic_string<>(and its specializations std::stringand std::wstring), etc. -- two verydifferent headers.

编辑:为了澄清关于cstringstring头文件的混淆,cstringC 运行时库的内容拉string.hstd命名空间;stringC++ 标准库的一部分,包含getline, std::basic_string<>(及其专业化std::stringstd::wstring)等——两个非常不同的头文件。

回答by pighead10

As ildjarn points out, the function is declared in <string>, and I'm suprised you didn't get an error at:

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

string line;

Also, this:

还有这个:

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

is not the way to write a read loop. You MUST test the success of the read operation, not the current stream state. You want:

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

while( getline(ifile,line) ) {
}

回答by FrostByte

this is happening because getline comes from the string library, you need to #include <string>or #include <cstring>

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