当 cin 读取数据时,它会传递并忽略任何前导白色空格字符(空格、制表符或换行符)。一旦它接触到第一个非空格字符即开始阅读,当它读取到下一个空白字符时,它将停止读取。
(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.
代码如下(示例):
// extract to string
#include
#include
int main ()
{
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Hello, " << name << "!\n";
return 0;
}
代码如下(示例):
getline(cin,line,'#');
表示遇到#停止读入
本文作者:WeSiGJ
参考链接(包括但不限于):
http://c.biancheng.net/view/1345.html
https://www.cnblogs.com/overcode/p/4126799.html
http://www.cplusplus.com/reference/string/string/getline/