当输入1执行程序后。再次运行输入2 cin.sync()无法清空输入缓冲区中的回车 会跳过if (ch == '2')中getline(cin, line);
#include<iostream>
#include<string>
using namespace std;
int main() {
string word, line;
cout << "请选择读取字符串的方式:1表示逐次读取,2表示整行读取" << endl;
char ch;
cin >> ch;
if (ch == '1')
{
cout << "您选择的逐次读取!";
cout << "请输入字符串: Welcome to C++ family" << endl;
cin >> word;
cout << "系统读取的有效字符串是:" << endl;
cout << word << endl;
return 0;
}
//清空缓冲区
cin.clear();
cin.sync();
//cin.ignore();
if (ch == '2')
{
cout << "您选择的是整行读取!";
cout << "请输入字符串: Welcome to C++ family" << endl;
getline(cin, line);
cout << "系统读取的有效字符是:" << endl;
cout << line << endl;
return 0;
}
cout << "您的输入有误!";
return -1;
cin.clear();
cin.sync();