C ++开关语句。默认不起作用

时间:2014-02-15 20:51:01

标签: c++

我一直在寻找和尝试不同的东西一小时,但无法弄清楚这一点。为什么我的默认工作不正常?如果我输入1-4,则输出符合预期。但是,如果我输入任何其他数字或字母,则不显示任何内容。如果我输入任何其他数字或字母,我希望显示默认值。

已解决:这是我的编译器。从现在开始只使用Visual Studio。 (VS最初没有显示我的默认值,因为我使用的不正确。)感谢大家的回复。

我的代码:

int main()
{
  int num;

cout << "Please enter the code stamped on the storage drive (1-4): ";
cin  >> num;

switch (num)
{
       case 1:
            cout << "The code you entered was 1; therefore, the storage capacity is 2GB." << endl;
            break;
       case 2:
            cout << "The code you entered was 2; therefore, the storage capacity is 4GB." << endl;
            break;
       case 3:
            cout << "The code you entered was 3; therefore, the storage capacity is 16GB." << endl;
            break;
       case 4:
            cout << "The code you entered was 4; therefore, the storage capacity is 32GB." << endl;
            break;
        default:
            cout << "Invalid selection - Please input 1 to 4 only.";
            break;

}           //end of switch


return 0;
}

3 个答案:

答案 0 :(得分:4)

default 正在工作(我已对其进行了测试),但需遵守以下注意事项。

首先,您的代码的结构方式,您必须输入某些内容。如果您只是按回车键,则不会发生任何事情,因为cin >> num将继续等待号码。

其次,当您输入任何不是数字的内容时,cin >> num会失败,并且num会保持未初始化状态。这导致switch中的undefined behaviour

您应该初始化num(比如0或其他无效值)和/或检查cin >> num是否成功:

if (cin >> num) {
  // the read has succeeded
} else {
  // the read has failed
}

答案 1 :(得分:0)

尝试在默认邮件的末尾添加'\n'<< endl

看起来default中的文字正在等待刷新。

您还可以在程序结束前添加cout.flush();

答案 2 :(得分:-4)

我知道这是暂时的说法毫无意义,但对于那些有类似问题的人来看你的代码....案例1:应该改为案例'1':这同样适用于其他所有人case,然后你的switch语句将起作用

相关问题