为什么 printf 在无限循环之前不起作用?
我正在尝试制作一个小程序,其中包含一个无限循环来等待用户的信号输入。我想在开始无限循环之前打印出有关当前工作目录的消息。该消息自行工作,但是当我将无限循环放入代码中时,该消息不会打印出来(但终端确实无限循环)。代码是:
#include <stdio.h>
int MAX_PATH_LENGTH = 100;
main () {
char path[MAX_PATH_LENGTH];
getcwd(path, MAX_PATH_LENGTH);
printf("%s> ", path);
while(1) { }
}
如果我取出 while(1) { }
我得到输出:
ad@ubuntu:~/Documents$ ./a.out
/home/ad/Documents>
这是为什么?谢谢你!
I am trying to make a small program that includes an infinite loop to wait for signal input from the user. I wanted to print out a message about the current working directory before beginning the infinite loop. The message works on its own, but when I put the infinite loop into the code the message does not print out (but the terminal does loop infinitely). The code is:
#include <stdio.h>
int MAX_PATH_LENGTH = 100;
main () {
char path[MAX_PATH_LENGTH];
getcwd(path, MAX_PATH_LENGTH);
printf("%s> ", path);
while(1) { }
}
If I take out while(1) { }
I get the output:
ad@ubuntu:~/Documents$ ./a.out
/home/ad/Documents>
Why is this? Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当您调用
printf
时,输出不会立即打印;相反,它进入幕后某处的缓冲区。为了真正让它显示在屏幕上,您必须调用 fflush 或等效的方法来刷新流。每当您打印换行符*以及程序终止时,都会自动为您完成此操作;当您删除无限循环时,第二种情况会导致字符串显示。但是有了循环,程序永远不会结束,因此输出永远不会刷新到屏幕上,并且您看不到任何内容。*正如我刚刚通过阅读评论中链接的问题itsmatt 发现的那样,刷新换行仅在程序打印到终端时发生,而不一定在打印到文件时发生。
When you call
printf
, the output doesn't get printed immediately; instead, it goes into a buffer somewhere behind the scenes. In order to actually get it to show up on the screen, you have to callfflush
or something equivalent to flush the stream. This is done automatically for you whenever you print a newline character* and when the program terminates; it's that second case that causes the string to show up when you remove the infinite loop. But with the loop there, the program never ends, so the output never gets flushed to the screen, and you don't see anything.*As I just discovered from reading the question itsmatt linked in a comment, the flush-on-newline only happens when the program is printing to a terminal, and not necessarily when it's printing to a file.
因为字符串末尾没有换行符。
stdout
默认情况下是行缓冲,这意味着它不会刷新到控制台,直到遇到换行符('\n'
),或者直到您使用fflush()
显式刷新它。Because you don't have a new-line character at the end of your string.
stdout
is line-buffered by default, which means it won't flush to console until it encounters a new-line character ('\n'
), or until you explicitly flush it withfflush()
.也许输出没有被刷新。尝试:
Perhaps the output is not getting flushed. Try:
因为标准输出还没有被刷新。
调用。
在循环之前
Because the stdout hasn't been flushed.
Call
before your loop.
因为输出没有被刷新。
在while循环前添加
即可解决问题。
Because the output is not flushed.
Add
before the while loop will solve the problem.