lundi 27 février 2017

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

So, 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. Solution with the same approach however 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. I would like to know 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. Any suggestions would be appreciated.

Aucun commentaire:

Enregistrer un commentaire