C++开关语句.默认值不起作用
C++ switch statement. Default not working
我一直在寻找和尝试不同的东西一个小时,但无法弄清楚。为什么我的默认值不起作用?如果我输入 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 语句将起作用
相关文章:
- if 子句中的赋值不起作用
- 通过构造函数创建一些值并尝试添加到文档中使用 rapidjson 不起作用
- 我正在尝试解决一个需要数组总和值但代码不起作用的问题,我想做这样的事情
- Cuda 基本程序 (将值写入矩阵和 std:cout 不起作用) ;主功能不启动
- 默认标签显然在 switch 语句中不起作用
- 用于 AES-gcm 加密的 IV 中是否有不起作用的值?
- 为什么以下成员初始值设定项在c++中不起作用
- 将复制构造函数设置为默认值在继承自 QObject 时不起作用
- 我正在努力在随机数组中查找最小值,有人知道为什么我的代码不起作用?C++
- 自定义类型转换运算符在转发引用上调用时不起作用(当对象按值传递时有效)
- 检查字符串中的小写字符或空格.布尔值不起作用
- C++ 默认值在开关语句中不起作用
- 为什么在调用 memcpy 到 bool 值后 memcpy 到 int 不起作用
- C++:当我将值分配给缓冲区时,它不起作用
- 赋值不起作用,但带有取消引用运算符的地址起作用?
- 指针不起作用,返回地址不是值
- 更改生成文件中变量的值不起作用
- 更新对象中的值不起作用
- C++开关语句.默认值不起作用
- 默认值在我的交换机 (C++) 上不起作用