关于带开关的do-while语句

时间:2015-06-30 03:53:47

标签: 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;
}

如果我选错了,我想重试进度,我感到困惑,不知道该做什么,所以有人可以告诉我应该做什么,这样我就可以做到吗?

3 个答案:

答案 0 :(得分:1)

...首先

input =! 1 && input =! 2 && input != 3 && input != 4

......那些=!应为!=

其次,如果有人输入非数字输入,cin >> input将失败,所有未来的输入尝试都会立即失败 - 甚至没有等待用户再输入任何内容。您需要清除错误状态并忽略流中剩余的任何错误输入字符 - 例如直到行尾:

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

答案 1 :(得分:0)

如果您希望switch语句中断/退出,您需要确保在每个案例后添加休息时间。否则下面的所有内容都将被执行。 你混淆了!=(不等于)和写=!

#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;
            break;  // add break
        case 3:
            cout << "Instagram is Loading..." << endl;
            break;  // add break
        case 4:
            cout << "SnapChat is Loading..." << endl;
            break;  // add break
        default:
            cout << "Wrong Selection" << endl;
        }
    } while(input != 1 && input != 2 && input != 3 && input != 4); // != not =!

    return 0;
}

答案 2 :(得分:0)

在每个break之后添加case语句:

case 2:
cout << "Twitter is Loading..." << endl;
break; 
case 3:
cout << "Instagram is Loading..." << endl;
break;

=!更改为!=

while(input != 1 && input != 2 && input != 3 && input != 4);