文章目录
前言一、getline()函数的定义二、getline()函数的使用1.可读取整行,包括前导和嵌入的空格,并将其存储在字符串对象中。2.char delim表示遇到这个字符停止读入,在不设置的情况下系统默认该字符为'\n',也就是回车换行符(遇到回车停止读入)。
总结
前言
当 cin 读取数据时,它会传递并忽略任何前导白色空格字符(空格、制表符或换行符)。一旦它接触到第一个非空格字符即开始阅读,当它读取到下一个空白字符时,它将停止读取。
一、getline()函数的定义
(1)
istream
& getline
(istream
& is
, string
& str
, char delim
);
istream
& getline
(istream
&& is
, string
& str
, char delim
);
(2)
istream
& getline
(istream
& is
, string
& str
);
istream
& getline
(istream
&& is
, string
& str
);
Get line from stream into string
Extracts characters from is
and stores them into str until the delimitation character delim is found
(or the newline character
, '\n', for (2)).
The extraction also stops
if the end of file is reached in is
or if some other error occurs during the input operation
.
If the delimiter is found
, it is extracted
and discarded
(i
.e
. it is
not stored
and the next input operation will begin after it
).
Note that any content in str before the call is replaced by the newly extracted sequence
.
Each extracted character is appended to the string as
if its member push_back was called
.
Parameters
is
istream object from which characters are extracted
.
str
string object where the extracted line is stored
.
The contents in the string before the call
(if any
) are discarded
and replaced by the extracted line
.
二、getline()函数的使用
1.可读取整行,包括前导和嵌入的空格,并将其存储在字符串对象中。
代码如下(示例):
#include <iostream>
#include <string>
int main
()
{
std
::string name
;
std
::cout
<< "Please, enter your full name: ";
std
::getline
(std
::cin
,name
);
std
::cout
<< "Hello, " << name
<< "!\n";
return 0;
}
2.char delim表示遇到这个字符停止读入,在不设置的情况下系统默认该字符为’\n’,也就是回车换行符(遇到回车停止读入)。
代码如下(示例):
getline(cin
,line
,'#');
表示遇到#停止读入
总结
我们可以使用stringstream来从一行英语we are the best!拆分成各个单词, 也可以使用getline()来获取某行的相关信息,还可以添加停止读入位。
本文作者:WeSiGJ
参考链接(包括但不限于): http://c.biancheng.net/view/1345.html https://www.cnblogs.com/overcode/p/4126799.html http://www.cplusplus.com/reference/string/string/getline/