简体   繁体   English

C:scanf 和 printf 的问题

[英]C: Problems with scanf and printf

I'm having issues with accepting user input and the printing its ascii value in C.我在接受用户输入和在 C 中打印其 ascii 值时遇到问题。 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).我的任务是编写一个程序,该程序只需将单个字符作为输入并打印出其 ascii 值,并且仅在用户输入 0 时停止(0 的 ascii 值为 48)。 My problem is that if the the printf seems to function one loop behind scanf.我的问题是,如果 printf 似乎 function 在 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:使用相同的输入,我希望 output 为:

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. \n字符是问题的根本原因。
Change改变

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

to

 scanf(" %c",&thisChar);  

EDIT: OP asked why a space before %c in scanf matters in output?编辑:OP 询问为什么在 output 中scanf%c之前的空格很重要?

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.当您将数据输入到程序并按Enter键时,额外的字符\n将与输入数据一起传递到输入缓冲区。 For Ex: If you want to enter f in your program then on pressing Enter key, input buffers contains f\n .例如:如果您想在程序中输入f然后按Enter键,输入缓冲区包含f\n On first iteration of loop, character f is read by scanf leaving behind the \n in the buffer.在循环的第一次迭代中,字符fscanf读取,并在缓冲区中留下\n On next iteration of loop, this \n is read by the scanf causing unexpected output.在循环的下一次迭代中,这个\nscanf读取,导致意外的 output。
To solve this issue you need to consume this \n before next read.要解决此问题,您需要在下次阅读之前使用此\n Placing a space before %c specifier in scanf can consume any number of new-line characters.scanf中的%c说明符之前放置一个空格可以消耗任意数量的换行符。

Did you consider using just getchar(3) ?您是否考虑过只使用getchar(3) (Perhaps fflush(3) could be needed)... Also stdin in a terminal is a complex beast. (也许fflush(3)可能需要)......终端中的标准输入也是一个复杂的野兽。 See tty demystified .请参阅tty 揭秘

The kernel (not only the libc ) is sort of buffering each tty lines (see line discipline ). kernel (不仅是libc )有点缓冲每个 tty 行(请参阅行规则)。

See also ncurses and GNU readline .另请参阅ncursesGNU readline

Dont use \n in scanf().不要在 scanf() 中使用 \n。

Remove "\n" and execute删除“\n”并执行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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