0
我一直在嘗試在類的程序上工作,但由於某種原因,當我輸入程序的第一個號碼時,它會轉到第一種情況,但它不會'讓我輸入一個字符串並直接回到菜單。 Ex)輸入1的結果是:輸入一個字符串:01.添加號碼,但忽略任何不是數字的內容。 如果我使用常規的cin語句,代碼將會非常好地執行。我不明白爲什麼這樣做。有人可以幫忙嗎?cin.getline()與switch語句不能配合使用
#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;
}
不要使用字符數組,使用std :: string後面。 –