这个问题在这里已有答案:
新手试图在这里自学C .
以下是供参考的代码:
#include
void function1(int);
void function2(int);
void function3(int);
using namespace std;
int main() {
int input = 0;
while (input != 4){
cout << "Prompt" << endl;
cin >> input;
switch(input) {
case 1:
function1(input);
break;
case 2:
function2(input);
break;
case 3:
function3(input);
break;
case 4:
cout << "Program terminated." << endl;
return 0;
break;
default:
cout << "Invalid input." << endl;
input = 4; // Exits the while-loop.
break;
}
}
}
void function1(int a) {
int prompt;
cout << "Prompt again" << endl;
cin >> prompt;
if (!cin){
cout << "Input is not a number." << endl;
return;
}
}
void function2(int a) {
}
void function3(int a) {
}
我要做的是创建一个function1来检测特定输入是字符串还是char而不是整数,然后说它不是数字,然后返回switch case语句 . 一旦它检测到这一点,while循环中的语句将永远继续并完全绕过cin提示!我从阅读其他人的问题中了解到,无限循环可能与在 Headers 中使用'int'并在预期填充时输入字符串有关,但我不明白为什么代码在cin时不会停止被提示或如何绕过它 . 有帮助吗?