我为课写了这个,当你输入这封信时,它应该返回与角色有关的气体。到目前为止,无论有什么人帮忙,我都只能让屏幕返回“未知”。
#include <stdio.h>
int
main(void)
{
char color; /* input- character indicating gass */
// Color of the gas
printf("Enter first letter of the color of cylinder > ");
scanf_s("%c",&color); /* scan first letter */
/* Display first character followed by gas */
printf("The gas in the cylinder is %c", color);
switch (color)
{
case 'O':
case 'o':
printf("Ammonia\n");
break;
case 'B':
case 'b':
printf("Carbon Monoxide\n");
break;
case 'Y':
case 'y':
printf("Hydrogen\n");
break;
case 'G':
case 'g':
printf("Oxygen\n");
break;
default:
printf("unknown\n");
}
return(0);
}
答案 0 :(得分:2)
'int'可能是4个字节,而交换机只查看一个字节。因此,开关可能只能看到高位0x00字节的颜色。我尝试的第一件事就是将颜色从int更改为char。
答案 1 :(得分:1)
你有什么理由要使用scanf_s()吗?
这有效:
#include <stdio.h>
int
main(void)
{
int color; /* input- character indicating gass */
// Color of the gas
printf("Enter first letter of the color of cylinder > ");
color=getchar(); /* scan first letter */
/* Display first character followed by gas */
printf("The gas in the cylinder is %c\n", color);
switch (color)
{
case 'O':
case 'o':
printf("Ammonia\n");
break;
case 'B':
case 'b':
printf("Carbon Monoxide\n");
break;
case 'Y':
case 'y':
printf("Hydrogen\n");
break;
case 'G':
case 'g':
printf("Oxygen\n");
break;
default:
printf("unknown\n");
}
return(0);
}
c02kt3esfft0:~ mbobak$ ./test
Enter first letter of the color of cylinder > o
The gas in the cylinder is o
Ammonia
c02kt3esfft0:~ mbobak$ ./test
Enter first letter of the color of cylinder > b
The gas in the cylinder is b
Carbon Monoxide
c02kt3esfft0:~ mbobak$ ./test
Enter first letter of the color of cylinder > y
The gas in the cylinder is y
Hydrogen
c02kt3esfft0:~ mbobak$ ./test
Enter first letter of the color of cylinder > g
The gas in the cylinder is g
Oxygen
c02kt3esfft0:~ mbobak$ ./test
Enter first letter of the color of cylinder > q
The gas in the cylinder is q
unknown
答案 2 :(得分:0)
这是因为你正在将一个字符读入未初始化的整数,这将导致未定义的行为。
答案 3 :(得分:0)
不是C编码器,但它看起来像你在将字符转换为整数?这就是它无法切换的原因 - 它将char与int进行比较。
答案 4 :(得分:0)
您对scanf_s
的致电应如下:
char color;
scanf_s("%c",&color,1);
这对我有用。