#include <iostream>
using namespace std;
int main() {
cout << "1. Facebook" << endl;
cout << "2. Twitter" << endl;
cout << "3. Instagram" << endl;
cout << "4. SnapChat" << endl;
int input;
do {
cout << "Enter a selection > ";
cin >> input;
switch(input) {
case 1:
cout << "Facebook is Loading..." << endl;
break;
case 2:
cout << "Twitter is Loading..." << endl;
case 3:
cout << "Instagram is Loading..." << endl;
case 4:
cout << "SnapChat is Loading..." << endl;
break;
default:
cout << "Wrong Selection" << endl;
}
}while(input =! 1 && input =! 2 && input != 3 && input != 4);
return 0;
}
如果我选错了,我想重试进度,我很困惑,不知道该怎么做,所以有人可以告诉我我应该怎么做才能成功吗?
最佳答案
首先...
input =! 1 && input =! 2 && input != 3 && input != 4
...那些=!
应该是 !=
.
其次,如果有人键入非数字输入,cin >> input
将会失败,并且所有 future 的输入尝试都会立即失败 - 甚至无需等待用户进一步输入任何内容。您需要清除错误状态并忽略流中剩余的任何错误输入字符 - 直到行尾:
default:
cout << "Wrong Selection" << endl;
std::cin.clear(); // clear error state
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');.
您需要 #include <limits>
在你的程序上使用 std::numeric_limts<>
.
另外,你是前两个case
语句缺少 break
并将失败以执行以下 case
(s) 代码....
我建议明确检查 cin >> input
为了成功,尽管使用 C++11 它保证设置 input
至 0
失败时它会可靠地工作。使用 C++03 就没有这样的保证,你可能会在 input
中留下任意垃圾。失败后,这可能恰好匹配 case
之一秒。要明确处理此问题:
if (!(cin >> input)) input = -1; // sentinel meaning erroneous
关于c++ - 关于带 switch 的 do-while 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31129225/