2
votes

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?

3
change "%c\n" to " %c" - BLUEPIXY
Always check return value of scanf family of functions! - hyde
note that ascii == '0' is absolutely equivalent to ascii == 48 only that it is easier to understand what your code is supposed to mean. - VoidStar

3 Answers

2
votes

\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.

0
votes

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.

0
votes

Dont use \n in scanf() .

Remove "\n" and execute