Rizzo Rizzo -4 years ago 88
C Question

What is the difference between the following two uses of `putchar`?

I was writing some code where I was getting an unexpected output in one part of the program, which in turn disrupted the entire system.

The code can be simplified and shortened to:

char ch;
printf("Enter Number: ");

while ((ch = getchar()) != '\n') {
if (ch >= 65 && ch <= 67) {
ch = 2;
}
putchar(ch);
}


As per the code above, I am trying to print a character/integer sequence of the user's choice. The numbers should remain unchanged whereas if the user enters letter
A
, then this should print
2
.

Expected Output

Enter Number: 23-AB
23-22


Actual Output

Enter Number: 23-AB
23-☺☺


Once confronted with this problem, I decided to tweak some things and came up with the following code which worked perfectly. It uses the same approach but produces different output:

char input;
printf("\nEnter Number: ");

while ((ch = getchar()) != '\n') {

switch (toupper(ch)) { //toupper function not really needed since I am expecting the user to enter upper-case letters ONLY
case 'A': case 'B': case 'C':
printf("2");
break;
default:
putchar(ch);
}
}


Expected Output

Enter Number: 23-AB
23-22


Actual Output

Enter Number: 23-AB
23-22


I am unable to comprehend why I am failing to convert the ASCII value of the characters entered in the first code to a single integer. What is the reason for this difference in the outputs? I have simply changed the type of controlling expression, from
if-statement
to a
switch-statement
(or so I think). How can I alter the first code to provide me with the same output as the second code?

Answer Source

In the first version, setting ch=2; makes ch the character with ASCII value 2, not the character 2. ch=0x32; in your first version would probably work, since ASCII 50 = 0x32 is character 2. Even easier (and better, as Weather Vane points out) is ch='2';.

In your second version, you are using printf("2"). As a result, the compiler is producing the ASCII value for you when it processes the string "2", just as it would for ch='2';. Try printf("%d\n",'2'); and you should see 50.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download