cin.getline() 不适用于 switch 语句

cin.getline() isn't working with switch statement

本文关键字:适用于 switch 语句 不适用 getline cin      更新时间:2023-10-16

我一直在尝试为课程上的程序工作一个字符串,直接回到菜单。ex)输入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] != '')
{
    if(isalpha(line[size2]))
    {
        line[size2] = 0;
    }
    sum += line[size2];
    size2++;
}
cout << sum;
}

此语句之后

cin >> choice;

使用

#include <limits>
//...
cin >> choice;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), 'n' );