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

C++ switch statement. Default not working

本文关键字:不起作用 默认值 语句 开关 C++      更新时间:2023-10-16

我一直在寻找和尝试不同的东西一个小时,但无法弄清楚。为什么我的默认值不起作用?如果我输入 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;
}

default 正在运行(我已经测试过了),但需要注意以下事项。

首先,你的代码结构方式,你必须输入一些东西。如果您只按 Enter 键,则不会发生任何事情,因为cin >> num将继续等待号码。

其次,当您输入任何不是数字的内容时,cin >> num失败并num未初始化。这导致switch中的行为未定义。

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

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

尝试在默认消息的末尾添加'n'<< endl

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

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

我知道

这毫无意义地说,因为这是不久前的事情,但对于那些有类似问题的人,看看你的代码......情况 1:它应该代替 情况"1":同样适用于其他所有情况,然后您的 switch 语句将起作用