std::getline
来自cppreference.com
< cpp | string | basic string
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
在头文件 <string> 中定义
|
||
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input, |
(1) | |
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>&& input, |
(1) | (C++11 起) |
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input, |
(2) | |
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>&& input, |
(2) | (C++11 起) |
getline
从输入流中读取字符,并把它们转换成字符串原文:
getline
reads characters from an input stream and places them into a string:1)
的行为就像
UnformattedInputFunction
,除了input.gcount()
不会受到影响。在构造和检查岗哨对象的,执行以下操作:原文:
Behaves as
UnformattedInputFunction
, except that input.gcount()
is not affected. After constructing and checking the sentry object, performs the following:1)
调用str.erase()
2)
input
并把它们添加到str
的字符提取出来,直到发生以下情况之一中列出的顺序进行检查原文:
Extracts characters from
input
and appends them to str
until one of the following occurs (checked in the order listed)a)
b)
下一个可用的输入字符
delim
,Traits::eq(c, delim),在这种情况下,分隔符是从input
提取进行了测试,但不会追加到str
.原文:
the next available input character is
delim
, as tested by Traits::eq(c, delim), in which case the delimiter character is extracted from input
, but is not appended to str
.c)
3)
2)
同getline(input, str, input.widen(’\n’)),也就是默认的分隔符是底线字符.
原文:
Same as getline(input, str, input.widen(’\n’)), that is, the default delimiter is the endline character.
[编辑] 参数
input | - | 流中获取数据
|
str | - | 把数据转换成字符串
|
delim | - | 分隔符
|
[编辑] 返回值
input
[编辑] 示例
下面的代码要求用户输入他们的名字,然后迎接他们用这个名字.
原文:
The following code asks the user for their name, then greets them using that name.
#include <string> #include <iostream> int main() { std::string name; std::cout << "What is your name? "; std::getline(std::cin, name); std::cout << "Hello " << name << ", nice to meet you."; }
Possible output:
What is your name? John Q. Public Hello John Q. Public, nice to meet you.