简体   繁体   English

C语言中奇怪的scanf问题

[英]Weird scanf issue in C

Let's say that I use scanf to, for example, read a character from the keyboard. 假设我使用scanf例如从键盘读取字符。 After that I use printf to print the character I just read. 之后,我使用printf打印我刚刚阅读的字符。

scanf("%c",&ch);
printf("%c",ch);

When scanf is reading the character, I must press enter to continue and run the printf , right? scanf读取字符时,我必须按Enter键才能继续并运行printf ,对吗?

And let's say I enter ABCD with the keyboard. 假设我用键盘输入ABCD After that printf will print A . 之后, printf将打印A

But when I do this: 但是当我这样做时:

do {
   scanf("%c",&ch);
   printf("%c",ch);
} while (ch!='\n');

and enter ABCD with the keyboard, I assume that the printf must print A . 并使用键盘输入ABCD ,我认为printf必须打印A And because A is not \\n it will continue the loop, right? 而且由于A不是\\n ,它将继续循环,对吗?

But instead of this it will print ABCD . 但是相反,它将打印ABCD Why does this happen? 为什么会这样?

When you type in "ABCD\\n" , each scanf("%c",&ch); 当您键入"ABCD\\n" ,每个scanf("%c",&ch); reads one char from the input buffer, until the newline is reached. 从输入缓冲区读取一个char ,直到到达换行符。

So after the 'A' is printed, there is still a "BCD\\n" in the buffer, so that the next scanf immediately succeeds reading another char , 'B' in the next iteration of the loop. 因此,在打印出'A' "BCD\\n"之后,缓冲区中仍然有一个"BCD\\n" ,因此下一个scanf立即在循环的下一次迭代中成功读取另一个char'B'

in scanf i must press enter to continue and run the printf right? 在scanf中,我必须按Enter键才能继续并运行printf对吗?

Nope. 不。 As long as there is a character to be read, it will be read. 只要有一个要读取的字符,它就会被读取。

i put in scanf ABCD after that printf will print A ... 我将scanf ABCD放在scanf ABCD之后将打印A ...

If you input ABCD and enter, the input will now contain five characters. 如果输入ABCD并输入,则输入现在将包含五个字符。 A, B, C, D and a newline. A,B,C,D和换行符。 Your cycle will read the characters A, B, C, D in sequence and then read the newline. 您的循环将按顺序读取字符A,B,C,D,然后读取换行符。

scanf does not wait for you to press enter, it simple tries to read in what you typed if it matched your format string. scanf不会等待您按Enter键,它会简单地尝试读取与格式字符串匹配的键入内容。 If you had used %s , then it would wait until a whitespace character before matching. 如果您使用了%s ,那么它将等到一个空格字符再进行匹配。

This thread may also be useful: why does scanf not wait for user input after it fails one time? 该线程可能也很有用: 为什么scanf一次失败后不等待用户输入?

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

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