【发布时间】:2014-04-22 03:50:51
【问题描述】:
我要做的是让终端打印出一个字符串,暂停,然后覆盖该字符串。但实际情况是,程序只是简单地打印出最终结果,而不显示第一个字符串。
我以为我可以使用sleep 来执行此操作,但它不起作用。为什么不呢?
#include <stdio.h>
#include <unistd.h>
int main(void){
char message[] = "Hello there";
int messageLength = sizeof(message);
int i;
printf("Hello, Dave.");
sleep(2);
for(i = 0; i < messageLength; i++)
printf("\b");
printf("Anyone there?\n");
return 0;
}
更新版本,感谢回答:
#include <stdio.h>
#include <unistd.h>
#include <time.h>
void twprint(char* output, int outputLength, struct timespec* delay);
void twbackspace(int length, struct timespec* delay);
int main(void){
char message1[] = "Hello, Dave.";
char message2[] = "Are you there, Dave?";
char message3[] = "I heard you talking in the pod.";
char message4[] = "Dave?";
struct timespec duration = { .tv_sec = 0, .tv_nsec = (100 * 1000 * 1000) };
/* ^ .tv_nsec = one hundred million nanoseconds */
twprint(message1, sizeof(message1)/sizeof(char), &duration);
sleep(2);
twbackspace(sizeof(message1)/sizeof(char), &duration);
twprint(message2, sizeof(message2)/sizeof(char), &duration);
sleep(2);
twbackspace(sizeof(message2)/sizeof(char), &duration);
twprint(message3, sizeof(message3)/sizeof(char), &duration);
sleep(2);
twbackspace(sizeof(message3)/sizeof(char), &duration);
sleep(2);
duration.tv_nsec *= 5;
twprint(message4, sizeof(message4)/sizeof(char), &duration);
printf("\n");
return 0;
}
void twprint(char* output, int outputLength, struct timespec* delay){
int i;
struct timespec remaining; /* dummy parameter */
for(i = 0; i < outputLength; i++){
printf("%c", output[i]);
fflush(stdout);
nanosleep(delay, &remaining);
}
}
void twbackspace(int length, struct timespec* delay){
int i;
struct timespec remaining; /* dummy parameter */
for(i = 0; i < length; i++){
printf("\b \b");
fflush(stdout);
nanosleep(delay, &remaining);
}
}
【问题讨论】:
-
您在 for 循环中删除了您的消息,这就是原因。
-
@valter,你不是说吗? :D
-
@valter 这就是为什么?你有没有读过 OP 想要做什么?
-
@JimBalter 他给了我一个很好的笑声。
标签: c io terminal sleep backspace