3

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;
}
Aquila
  • 29
  • 4
  • Does this answer your question? [Convert ASCII Value directly to the literal integer value](https://stackoverflow.com/questions/23352003/convert-ascii-value-directly-to-the-literal-integer-value) – Karl Knechtel Apr 30 '21 at 16:11
  • 1
    Hint: what happens if you try hard-coding `int num = '0';` (notice the quotation marks) instead of reading it in? – Karl Knechtel Apr 30 '21 at 16:12
  • Try `printf("%d -> %c\n", '6', 54);`. Maybe that will clarify. (Or it will just be confusing!) – William Pursell Apr 30 '21 at 16:13

2 Answers2

3

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');
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
2

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);
Mozz
  • 318
  • 2
  • 8