-2

So my problem is this I want to print numbers that come from the terminal while the numbers are different than the EOF.

For example if put 007 as the input, I want the output to be 7 or if I put 42 I want the output to be 42.

But for some reason, the output I get is a random number, that I cant understand.

program:

#include <stdio.h>

void ex04();

int main() {
    ex04();

return 0;
}

void ex04() {
    int c;
    c = getchar();
    while (c != EOF) {
        printf("%d\n",c);
        c = getchar();
    }
}

Input: 007

my Output:

           48
           48
           55
           10

Correct Output: 7

Any help would be appreciated.

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
Martim Correia
  • 483
  • 5
  • 16
  • 6
    Hint: `'0' == 48`, `'7' == 55` and `'\n' == 10`. Are you familiar with [ASCII](http://www.asciitable.com/)? – Brian61354270 Mar 19 '20 at 21:31
  • Brian got it correct. You are getting single chars. What you want is to print them as _chars_ and _not_ the decimal/ASCII code value. So, use `printf("%c\n",c);` Or, you could [for understand/debug purposes] do: `printf("%2.2X %c\n",c,c);` This would print the ASCII hex value in addition the the char itself. – Craig Estey Mar 19 '20 at 21:37

1 Answers1

3

getchar is designed to input a single character including white space characters as for example the new line character '\n' that has the code 10.

So if you are entering for example the number 42 then the first call of getchar returns the character '4' that has the ASCII code 52 and the second call - the character '2' that has the ASCII code 50.

Instead use the function scanf as for example

for ( int c; scanf( "%d", &c ) == 1; ) {
    printf("%d\n",c);
}

Pay attention to that there is a typo in your question

my Output:

           48
           48
           58
           10

Correct Output: 7

The ASCII code of the character '7' is 55 not 58.:)

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335