c++ - 关于带 switch 的 do-while 语句

标签 c++

#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 它保证设置 input0失败时它会可靠地工作。使用 C++03 就没有这样的保证,你可能会在 input 中留下任意垃圾。失败后,这可能恰好匹配 case 之一秒。要明确处理此问题:

if (!(cin >> input)) input = -1; // sentinel meaning erroneous

关于c++ - 关于带 switch 的 do-while 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31129225/

相关文章:

c++ - 如何计算两个圆相交的面积?

c++ - 如何检查一个结构是否有某个变量?

c++ - 优化此代码块

c++ - 无法在 SDL 2.0 中加载多个纹理

c++ - C++ 中的默认值取决于其他输入参数

c++ - 模板问题

c++ - 变量模板链接失败

C++ 运算符重载?

c++ - 创建字符指针 vector 以指向字符串 vector

c++ - Boost 文件系统教程无法编译