why does the getchar() function not work here?

Viewed 54

I'm trying to write C code where it takes in integer inputs, and prints them, unless the newline character ('\n') is entered.

But it never returns the value that I enter. If I enter 6, I expect it to print 6 but it gives me 54. In fact whatever number I expect, it gives me 48+(my number). Please help!

Here's my code:

#include <stdio.h>
int main(int argc, char *argv[])
{
   int counter = 0;
   int num; 
   while (counter <=1)
   {
       num = getchar();
       if (num == '\n')
       {
           break;
       }
       counter+=1;
       printf("%d", num);
   }
    return 0;
}
2 Answers

It looks like an ASCII code for your characters is printed.

Use %c to print one character:

printf("%c", num);

Or subtract '0' (the character code of 0) from the value to convert digit characters to the corresponding integer:

printf("%d", num - '0');

That's because you are printing the ascii equivalent of the integer. You can either typecast the input you get, i.e, int(num) after you read it or you can use scanf like this:

int num;
scanf("%d", &num);
Related