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
std has no member 'getline'?
提问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::getline
is defined in the string
header.
std::getline
在string
头文件中定义。
#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 cstring
and string
headers, cstring
pulls the contents of the C runtime library'sstring.h
into the std
namespace; string
is part of the C++ standard libraryand contains getline
, std::basic_string<>
(and its specializations std::string
and std::wstring
), etc. -- two verydifferent headers.
编辑:为了澄清关于cstring
和string
头文件的混淆,cstring
将C 运行时库的内容拉string.h
入std
命名空间;string
是C++ 标准库的一部分,包含getline
, std::basic_string<>
(及其专业化std::string
和std::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>