简体   繁体   中英

C: Problems with scanf and printf

I'm having issues with accepting user input and the printing its ascii value in C. I'm tasked with writing a program that simply takes a single char as input and prints out its ascii value, and only stops when the user inputs 0 (the ascii value of 0 is 48). My problem is that if the the printf seems to function one loop behind scanf.

while(x == 1){
    scanf("%c\n",&thisChar);
    ascii = thisChar;
    if(ascii == 48){
        x = -1;
    }
    printf("Ascii: %d\n", ascii);
}

For example, when I run this from the command line, I get something like this:

f  
0  
Ascii: 102  
f  
Ascii: 48  

and then the program ends. With those same inputs, I want the output to be:

f  
Ascii: 102  
0  
Ascii: 48  

and then end there. What is the error in my logic?

\n character is the root cause of your problem.
Change

 scanf("%c\n",&thisChar);  

to

 scanf(" %c",&thisChar);  

EDIT: OP asked why a space before %c in scanf matters in output?

When you inputs the data to a program and press Enter key, an extra character \n is passed to the input buffer along with the input data. For Ex: If you want to enter f in your program then on pressing Enter key, input buffers contains f\n . On first iteration of loop, character f is read by scanf leaving behind the \n in the buffer. On next iteration of loop, this \n is read by the scanf causing unexpected output.
To solve this issue you need to consume this \n before next read. Placing a space before %c specifier in scanf can consume any number of new-line characters.

Did you consider using just getchar(3) ? (Perhaps fflush(3) could be needed)... Also stdin in a terminal is a complex beast. See tty demystified .

The kernel (not only the libc ) is sort of buffering each tty lines (see line discipline ).

See also ncurses and GNU readline .

Dont use \n in scanf().

Remove "\n" and execute

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