逐个字符打印字符串,每个字符后有延迟

发布于 2024-12-11 17:04:03 字数 520 浏览 0 评论 0原文

我有一个有点愚蠢的问题,因为它应该非常简单......

假设我有字符串:

char *str = "stackoverflow";

我想一次打印一个字符,每个字符后有一些延迟:

int i = 0;
while (str[i] != '\0') {
  putchar(str[i]);
  usleep(100000);
  i++;
}

但是不是做明显且正确的事情,而是打印一个角色等待 100 毫秒,然后再重来一次,看起来延迟会累积起来并立即消失。
所以它快乐地睡了大约一秒半,然后打印出我的字符串。

有什么想法吗?
(我在 Ruby 中做了完全相同的事情,没有出现任何问题,并且还使用 '\r' 方法进行了尝试,该方法也适用于 Ruby ...)

请帮忙!
否则我无法完成我的作业的程序,即打印字符串;但我不想无聊地做...;)

谢谢!

I have a somewhat stupid problem because it's supposed to be utterly simple ...

Assume I have string:

char *str = "stackoverflow";

I want to print that string one character at a time with some delay after each character:

int i = 0;
while (str[i] != '\0') {
  putchar(str[i]);
  usleep(100000);
  i++;
}

But instead of doing the obvious and right thing, printing a character and waiting 100 ms and doing it over again, it looks like the delay gets accumulated and spit out at once.
So it sleeps happily for about one and a half second and then prints out my string.

Any ideas?
(I did the exact same thing in Ruby without a problem and also tried it using the '\r'-method, which also works in Ruby ...)

Please help!
Otherwise I can't do the program for my assignment, which is printing a string; but I don't want to do it boringly ... ;)

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夜深人未静 2024-12-18 17:04:03

尝试在两者之间刷新缓冲区:

putchar(str[i]);
fflush(stdout);
usleep(100000);

写入终端时,输出通常是行缓冲的。如果遇到 \n 或缓冲区已满,则会打印实际内容。

或者,您可以在开始时一劳永逸地禁用缓冲:

setbuf(stdout, NULL);

Try to flush the buffer in between:

putchar(str[i]);
fflush(stdout);
usleep(100000);

When writing to a terminal, output is usually line-buffered. The actual thing is printed if a \n is encountered or if the buffer fills.

Alternatively you could disable buffering once and for all at the beginning:

setbuf(stdout, NULL);
哭泣的笑容 2024-12-18 17:04:03

这不是累积并立即吐出的延迟,而是字符串(请注意,当您执行程序时,延迟出现在打印字符串之前,而不是之后)。

在每个字符后刷新标准输出:

fflush(stdout);

It's not the delay that gets accumulated and spit out at once, it's the string (note that when you execute your program, the delay comes before the string is printed, not after it).

Flush the standard output after each char:

fflush(stdout);
如此安好 2024-12-18 17:04:03

您需要调用fflush()。字符正在缓冲。

You need to call fflush(). The characters are getting buffered up.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文