[英]std::getline for an ifstream, using parameter string or char *
I am using fstream
to read or write into a file. 我正在使用
fstream
读取或写入文件。
I meet a problem regarding the function ifstream::getline
. 我遇到有关函数
ifstream::getline
。 When I include <string>
, then I can pass string as a parameter to the function, if not, I have to pass char*
as the parameter. 当我包含
<string>
,我可以将string作为参数传递给函数,如果没有,我必须将char*
作为参数传递。 Can someone tell me why? 有人可以告诉我为什么吗?
According to the description of the function, as I understand it, the right parameter waited should be char*
. 根据对函数的描述,据我了解,等待的正确参数应该是
char*
。 Is the string
value converted to a char*
here? string
值是否在这里转换为char*
?
String type isn't converted to char*
. 字符串类型不会转换为
char*
。 That's why .c_str()
exists. 这就是存在
.c_str()
的原因。 But the std::string type will accept a char*
as an initializer. 但是std :: string类型将接受
char*
作为初始化程序。
The two types aren't backwards compatible. 这两种类型不向后兼容。
std::string
's will accept char*
's but char*
's don't accept std::string
's. std::string
会接受char*
,但char*
不会接受std::string
。
There are two versions of std::getline()
: std::getline()
有两个版本:
std::istream::getline(char*, char = '\n'); // member function of istream
std::getline(std::istream&, std::string&, char = '\n'); // free function in <string>
When including the definition of std::istream
you obviously get the member function. 当包含
std::istream
的定义时,您显然会获得成员函数。 However, you'll need to include <string>
to get the definition of std::string
which also comes with its version of std::getline()
. 但是,您需要包含
<string>
以获得std::string
的定义,该定义也随其std::getline()
版本一起提供。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.