做练习题,每一道小题用函数写,并在主题程序中用循环结构调用。但是两个练习会要求输入字符 并多于需求。
cin缓冲区任然存在遗留的字符开头就是空字符,直接导致主程序结束,或者陷入死循环。
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int p5_8();
int p5_9();
int main()
{
int num;
cout << "code to use: ";
cin >> num;
while (num > 0)
{
if (num == 1)
p5_8();
else if (num == 2)
p5_9();
cout << "code to use: ";
//cin.get();
cin >> num;
}
return 0;
}
int p5_8()
{
char word[100];
int count = 0;
cout << "Enter words (to stop, type the word done):" << endl;
cin >> word;
while (strcmp(word, "done") != 0)
{
if (bool(cin >> word) == true)
count++;
}
cout << endl << "You entered a total of " << count << " words." << endl;
//cin.sync();
return 0;
}
int p5_9()
{
string word;
int count = 0;
cout << "Enter words (to stop, type the word done):" << endl;
cin >> word;
while (word != "done")
{
if (bool(cin >> word) == true)
count++;
}
cout << "You entered a total of " << count << " words." << endl;
//cin.sync();
return 0;
}
尝试使用cin.sync()清理也没有效果。
请问如何解决问题,使主程序能够正常循环