我一直在尝试为课程编写程序,但出于某种原因,当我输入程序的第一个时,它转到案例1但是它不允许我输入字符串并直接返回到菜单。例)输入1结果是:输入字符串:01。添加数字但忽略任何不是数字的数字。 如果我使用常规cin语句,代码将执行完全正常。我不明白为什么这样做。有人可以帮忙吗?
#include <iostream>
#include <cctype>
using namespace std;
void firstChoice(char []);
int main()
{
int choice;
int answer;
const int SIZE = 100;
char line[SIZE];
do
{
cout << "1. Adds numbers but ignores anything thats not a number." << endl;
cout << "2. Count the number of consonants in a string." << endl;
cout << "3. Counts the vowels in a string." << endl;
cout << "4. Counts whitespace characters in a string." << endl;
cout << "Enter a number to access that program or 0 to end it: ";
cin >> choice;
switch(choice)
{
case 1:
cout << "\nEnter a string: ";
cin.getline(line, SIZE);
firstChoice(line);
break;
case 2:
cout << "Enter a string: ";
cin.getline(line, SIZE);
break;
case 3:
cout << "Enter a string: ";
cin.getline(line, SIZE);
break;
case 4:
cout << "Enter a string: ";
cin.getline(line, SIZE);
break;
}
}
while(choice != 0);
return 0;
}
void firstChoice(char line[])
{
int size2 = 0;
int sum = 0;
while(line[size2] != '\0')
{
if(isalpha(line[size2]))
{
line[size2] = 0;
}
sum += line[size2];
size2++;
}
cout << sum;
}
答案 0 :(得分:2)
在此声明之后
cin >> choice;
使用
#include <limits>
//...
cin >> choice;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );