Reputation: 13
i wrote this for class, when you input the letter it should return the gas related to the character. So far i've only been able to get the screen to return "unknown" no matter what can anyone help.
#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);
}
Upvotes: 1
Views: 82
Reputation: 1
your call to scanf_s
should be as follows:
char color;
scanf_s("%c",&color,1);
This worked for me.
Upvotes: 0
Reputation: 14433
Is there some reason you want to use scanf_s()?
This works:
#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
Upvotes: 1
Reputation: 3062
Not a C coder, but it looks to me like you are casting the character to an integer? Which is why it can't switch - it's comparing a char with an int.
Upvotes: 0
Reputation: 22552
That is because you are reading a character into an uninitialized integer which will result in undefined behaviour.
Upvotes: 0
Reputation: 2130
It may be that 'int' is 4 bytes, while the switch is looking at only one byte. Thus the switch may only see the high order 0x00 byte of color. The first thing I'd try is changing color from int to char.
Upvotes: 2