scanf() 函数的魔力?
为什么运行这段代码并打印整个字符串?
#include <stdio.h>
void main()
{
int a;
while(a!='q')
{
scanf("%c",&a);
printf("%c",a);
}
}
输入除q之外的字符串,最后按回车键。现在您的字符串才会打印在屏幕上。为什么?
Why run this code and print whole string?
#include <stdio.h>
void main()
{
int a;
while(a!='q')
{
scanf("%c",&a);
printf("%c",a);
}
}
Enter string except q, and finally press enter key. Only now your string will print on the screen. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里的问题不在于 scanf,而在于您的 printf 调用。
Printf 会缓冲输出,直到到达新行,因此程序在
printf("\n");
之前不会显示任何内容。 (当有人按 Enter 时也会发生这种情况,您将他们的返回值输出到屏幕,这会导致缓冲区刷新。)如果您不想使用
printf("\n")
分解您的输出,然后您可以使用 fflush(stdout) 手动刷新缓冲区而不打印任何内容,如下所示:The problem here is not with scanf, it is with your printf call.
Printf buffers output until a new line is reached, so the program will not display anything until you
printf("\n");
. (Which also happens when someone presses enter, you output their return to the screen which causes the buffer to flush.)If you don't want to break up your output with
printf("\n")
, then you can usefflush(stdout)
to manually flush the buffer without printing anything, like this:对于初学者来说,该代码无法编译 - print 不是 C 中的函数, printf 是您正在寻找的函数。
至于我认为你要问的问题,我不知道你为什么要打印你读到的每个字符,直到你读到 q;这似乎有点毫无意义。
Well for starters, that code won't compile - print is not a function in C, printf is one one you're looking for.
As for what I think you are asking, I don't know why you would want to print every character you read until you read q; it seems kinda pointless.
首先,您需要将 a 定义为 char 类型:
当您按 Enter 时,while 循环将运行您输入的字符数。尝试以下操作看看发生了什么:
At first you need to define a to be of char type:
When you hit enter, the while loop will run for so many times as many characters you have inputed.Try this to see what is happening: