默认值仅适用于 8 和 9.之后,它使用第一个数字并将其视为 1,2,3
default only works for 8 and 9. after that it uses the first number and treats it as a a 1,2,3
default除了数字8和9之外不起作用。10 及以上它使用第一个整数,将其视为完全忽略其后面的第二个数字的情况。请帮忙
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char day;
cout << " Enter day of the week " << endl;
cin >> day;
switch (day)
{
case '1' : case '6' : case '7' :
cout << "weekend";
break;
case '2' : case '4' :
cout << "going to C++ Class";
break;
case '3' : case '5' :
cout << "studying for C++ Class";
break;
default :
cout << "invalid day number";
}
system("pause");
return 0;
}
当你写的时候
char day;
cin>>day;
它只接受输入中的一个字符。您应该将 day 声明为整数,您的问题将得到解决。
您只在 day
变量中存储一个字符,因为它被声明为 char
。 将其更改为 int
,并将 switch 语句中的大小写更改为int
值。
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int day;
cout << " Enter day of the week " << endl;
cin >> day;
switch (day)
{
case 1:
case 6:
case 7:
cout << "weekend";
break;
case 2:
case 4:
cout << "going to C++ Class";
break;
case 3:
case 5:
cout << "studying for C++ Class";
break;
default :
cout << "invalid day number";
}
system("pause");
return 0;
}
您的问题是将输入存储在char
中。
由于您将day
存储为 char,因此它仅足够大以存储任何输入的第一个字符。当你输入1
(或2
,或3
等(时,这很好,因为输入只有一个字符。当您输入一个具有多个数字的数字时,只能存储第一个字符 - 例如,如果您输入 10
,则只有空间存储1
。
要解决此问题,您应该对 day
使用更合适的数据类型。使用int
或类似的东西可能是最好的,因为这会给你足够的空间来容纳大值。因此,换句话说,将char day;
更改为int day;
。
但是,如果您这样做,则需要更改case
语句中的值以匹配 - 由于您不再比较字符,因此您也需要将它们更改为整数(例如,将'0'
更改为仅0
(。
char day;
cout << " Enter day of the week " << endl;
cin >> day;
您的代码说从标准输入中读取一个字符。如果这不是您想要执行的操作,请更改代码。
在决定变量的数据类型时,您需要非常小心,因为每种数据类型都有其固有属性。就像这里指出的每个人一样,您需要将数据类型从"char"更改为"int"。
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 如何仅读取文本文件中的第一个值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- OpenGL:第二个VBO破坏了第一个VBO
- 将一个数字拆分为多个数字,每个数字只有一个有效位
- 为什么第一个Dynamic_cast没有投射到基类?
- OpenGL 2D游戏只绘制第二个精灵纹理而不是第一个
- C++ 为什么程序只读取第一个值
- 在我的第一个C++程序中需要一些帮助(简单)
- 为什么我的代码在第一个 if 语句处中断?
- 是否可以从另一个类对象调用一个类函数而不继承第一个类
- 在将字符串转换为整数后,是否有一种方法可以保持数字的第一个零