[英]Reading from stdin, and clearing stdin afterward
這是一個循環,反復從stdin
獲取兩個字符並將其輸出。
char buf[2];
while (1)
{
printf("give me two characters: ");
fflush(stdout);
read(0, buf, 2);
printf("|%c%c|\n", buf[0], buf[1]);
}
問題在於,當在終端上敲擊ENTER鍵時,將插入一個換行符並將其保留在stdin
緩沖區中,並且將在下一次read
調用時被抓取。 理想情況下, stdin
調用read時,我都希望有一個清晰的stdin
緩沖區,而之前的垃圾都沒有遺漏。 您能為此推薦一個好的解決方案嗎?
我嘗試了各種庫調用,例如fgets
,但是它們遇到相同的問題。 我正在考慮使用fpurge
手動清除緩沖區,但是被告知這不是一個好的解決方案。
這里的問題是,剩余的輸入應視為垃圾,然后丟棄。 但是,當我下一個調用read
我無法將剩余的輸入與新的輸入區分開。
感謝您的輸入。
您可以添加getchar();。 閱讀更多“ \\ n”:
#include <stdlib.h>
#include <stdio.h>
char buf[2];
main() {
while (1)
{
printf("give me two characters: ");
fflush(stdout);
read(0, buf, 2);
getchar();
printf("|%c%c|\n", buf[0], buf[1]);
}
}
give me two characters: ab
|ab|
give me two characters: xy
|xy|
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.