//string类的输入运算符和getline函数分别是如何处理空白字符的。(string和getline函数对含有空白字符串的区别)
#include<iostream>
#include<string>
using namespace std;
int main()
{
string word, line;
//提示用户输入字符串
cout << "请选择读取字符串的方式: 1表示逐词读取, 2表示整行读取 " << endl;
//存放字符 '1' 或 '2'
char ch;
cin >> ch;
//判断是逐词读取还是整行读取
if (ch == '1')
{
//提示用户输入字符串
cout << "请输入字符串: Welcome to C++ family! " << endl;
cin >> word;
cout << "系统读取的有效字符串是: " << endl;
cout << word << endl;
system("pause");
return 0;
}
//清空输入缓冲区
cin.clear( );
cin.sync( );
if (ch == '2')
{
//提示用户输入字符串
cout << " 请输入字符串: Welcome to C++ family! " << endl;
getline(cin, line); //此getline函数用于接收回车符或者空格符
getline(cin, line); //此getline函数用于接收用户输入
cout << "系统读取的有效字符串是: " << endl;
cout << line << endl;
system("pause");
return 0;
}
//若非字符'1'和'2',则输入有误
cout << "您输入有误! " << endl;
system("pause");
return -1;
}
<C++ Primer_5th>习题_3.3
最新推荐文章于 2021-08-31 17:12:19 发布