cin输入字符串允许输入空白符
int main()
{
string s1;
cin >> s1;
return 0;
}
上述代码只能输入一个完整的,不加任何空白字符的字符串。输入中即使带了空白符也是不起作用的,只会输出空白符之前的字符串。有时候我们想输出带空白符的字符串,就像hello world
。
所以可以想到用下面的方式:
int main()
{
string s1;
char c;
while (cin >> c)
{
s1 += c;
}
cout << s1 << endl;
return 0;
}
上述方法虽然可以实现输出空白符后面的字符串,但是空白符被跳过了,所以输出结果是helloworld
。
本文将介绍几种c++
方式的读取空白符的方法
使用noskipws
noskipws
输入操作算子告诉输入流不要跳过空白符,就像提取其他任何字符一样。
int main()
{
string s1;
char c;
cin >> noskipws;
while (cin >> c)
{
s1 += c;
}
cout << s1 << endl;
return 0;
}
./a.out
hello i love u
ctrl + d // 终止本次输入
hello i love u
使用cin.getline()
getline()
方法用一行数据填充缓冲区,数据量最多为缓冲区指定的大小。指定的大小中包含'\0'
字符。
#define BUFFSIZE 64
int main()
{
char buff[BUFFSIZE]{0};
cin.getline(buff, BUFFSIZE); // 最多读取BUFFSIZE-1个字符
cout << buff << endl;
return 0;
}
std::getline()
这个函数定义在<string>
头文件中和std
命名空间中。它接收一个流引用、一个字符串引用。使用这个版本的getline()
函数的优点是不需要指定缓冲区的大小。
int main()
{
string s1;
getline(cin, s1);
cout << s1 << endl;
return 0;
}