简体   繁体   中英

Printing numbers in C

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.

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.:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM