[問題] 標準輸入重導向造成scanf的問題!

看板C_and_CPP作者 (Veck)時間12年前 (2012/04/08 01:10), 編輯推噓1(108)
留言9則, 3人參與, 最新討論串1/1
開發平台: FreeBSD 和 Windows 7 問題 - 一段code如下: #include<stdio.h> #include<stdlib.h> int main() { int input = 0; fflush(stdin); //想說清空input buffer scanf("%d",&input); printf("%d",input); return 0; } 當編譯完以後執行時:(test.txt 是一個不為空的純文字檔案) shell>./a.out 1 ---> 我的輸入 1 ---> printf 顯示 shell>./a.out < test.txt 0 --->printf顯示 shell> 直接就跳過了!!! 原本我想說應該是因為標準輸入造成buffer中還有資料 所以scanf讀到了 但是我有在scanf前面加上 fflush(stdin); 為什麼還是造成這樣的結果???? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.132.21.244

04/08 01:11, , 1F
fflush不應該用在stdin
04/08 01:11, 1F

04/08 01:16, , 2F
那應該怎麼用呢? 我有改成 stdout 過,也不行
04/08 01:16, 2F

04/08 01:17, , 3F
你的檔案內容是?
04/08 01:17, 3F

04/08 01:18, , 4F
name:Jack<TAB>phone:0911111111
04/08 01:18, 4F

04/08 01:27, , 5F
感謝 james大! 我終於 Google到了!
04/08 01:27, 5F

04/08 01:28, , 6F
在標準輸入前面加入stdin = fopen("/dev/tty","rb");就可
04/08 01:28, 6F

04/08 01:58, , 7F
同樣的慘劇在 #19nvgbVG 也發生過一次...
04/08 01:58, 7F

04/08 01:59, , 8F
話說那也不是正解吧._.
04/08 01:59, 8F

04/08 02:00, , 9F
為什麼你想在那個地方清空輸入 buffer 呢 ._.?
04/08 02:00, 9F
文章代碼(AID): #1FW7KJpG (C_and_CPP)