[英]Replace Printed Statement with timing sequence in C
我想創建一個程序以打印出第一個printf語句,然后在下一行中,將清除第一個printf語句並打印下一個語句。 請幫助我修復代碼。
printf("Please wait while Loading...");
Sleep(2132);
printf("Done Loading");
這應該工作:
printf("Please wait while Loading...");
fflush(stdout); // flush output, this is necessary on some platforms,
// otherwise the text won't be printed immediately
Sleep(2132);
printf("\rDone Loading \n"); // the \r returns to the start of the line,
// and the trailing spaces are necessary to
// erase the remaining text
此問題不特定於C(或與此有關的任何其他語言),而是特定於您要打印到的控制台 。
許多控制台可以理解回車符 ( \\r
)來將光標移動到當前行的開頭。 您可以嘗試使用它,並用空格“擦除”最后一條消息:
printf("Please wait while Loading...");
Sleep(1000);
printf("\r ");
printf("\rDone Loading\n");
笨拙地,您至少不能在便攜式C99或C11中達到所需。 BTW sleep
不是標准C(但在POSIX中)。 您可能需要一些操作系統特定的東西。 希望您使用的是Linux。
stdio(即標准C中的<stdio.h>
)僅定義了標准流和標准輸出的有限概念,比終端仿真器要簡單得多。
(例如,在Linux上,您的程序可能在某些命令管道中使用 ,例如yourprogram | grep foo | less
您想要的內容就沒有意義了)。
如果要編寫具有基於文本的界面的基於終端的應用程序,請使用一個庫。 在Linux和POSIX上將是ncurses 。 或者,您可以使用某些ANSI轉義碼和/或在某些有限情況下使用返回字符\\r
。 請記住,stdio已緩沖,因此您可能需要fflush(3) 。 閱讀tty揭秘和termios(3) 。
您甚至可能想要編寫圖形用戶界面代碼。 這應該在設計階段考慮(因為您的程序需要一些事件循環,因此會有不同的體系結構)。 然后使用小工具工具箱 ,例如GTK 。
假設stdout
是支持文本覆蓋的終端或窗口,那么簡單的解決方案是輸出'\\r'
(回車),用空格覆蓋,然后打印第二個字符串。
printf("Please wait while Loading...");
fflush(stdout);
Sleep(2132);
printf("\r");
/* output the number of space characters equal to length of the preceding string */
printf("\r");
printf("Done Loading");
fflush(stdout);
存在並非所有終端/窗口都正確支持此問題。 在這種情況下,您將需要使用特定於終端/窗口和主機系統的技術。 如果標准輸出已重定向到文件或管道,則此方法也可能不起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.