[問題] getchar()讀取輸入數據相關

看板C_and_CPP作者 (JJJ)時間6年前 (2018/05/27 15:37), 6年前編輯推噓1(105)
留言6則, 2人參與, 6年前最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) Mac 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) Xcode 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 剛剛在練習使用getchar() 先試著讀入以空格分隔的兩個數字 相加後輸出結果 這部分沒有問題 再來想練習連續輸入多組數字再一次輸出所有結果 因此增加一個for迴圈來實現此功能 結果每次可輸入的組數都會比設定的少一組 不確定是少考慮到哪個部分想請教一下 預期的正確結果(Expected Output): input times 3 //輸入 input number1 number2 1 2 //輸入 input number1 number2 3 4 //輸入 input number1 number2 5 6 //輸入 3 7 11 錯誤結果(Wrong Output): input times 3 //輸入 input number1 number2 input number1 number2 1 2 //輸入 input number1 number2 3 4 //輸入 -272599498 3 7 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) https://ideone.com/ZvJC9C #include <stdio.h> int main(int argc, const char * argv[]) { char c; int a[2]; int cnt; printf("input times\n"); scanf("%d", &cnt); int ans[cnt]; int space, temp, flag; for (int i=0; i<cnt; i++) { space=0; temp=0; flag=0; printf("input number1 number2\n"); while((c=getchar())!='\n') { if (c==' ') { a[space] = temp; space++; temp = 0; flag = 0; } else { flag = 1; temp = temp * 10 + (c-48); } } if(flag) a[space] = temp; ans[i] = a[0] + a[1]; } for (int i=0; i<cnt; i++) { printf("%d ", ans[i]); } } 補充說明(Supplement): https://ideone.com/9FTfUB 這是沒有使用for迴圈版本 到這步還沒有問題 再麻煩各位大大指導了,感謝! PS1: 已解決: https://ideone.com/OOf0md 解決方式: 再加一個getchar()把多的換行符號讀取掉 感謝K大~~ PS2: 後來發現讀兩個數字不用getchar() 只要用scanf一次讀兩個就好..... int n1, n2; scanf("%d%d", &n1, &n2); 希望其他新手不要跟我一樣傻.... -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.83.255.16 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1527406655.A.A9D.html ※ 編輯: jojojen (223.141.109.32), 05/27/2018 16:57:55

05/27 21:31, 6年前 , 1F
鍵盤輸入的整行字會先放到buffer,如果裡面還有剩, inpu
05/27 21:31, 1F

05/27 21:31, 6年前 , 2F
t相關函數優先從這buffer抓取。如果buffer 內容不足才會
05/27 21:31, 2F

05/27 21:31, 6年前 , 3F
發生等待鍵盤輸入。前面scanf讀走了一個%d,至少還有個\n
05/27 21:31, 3F

05/27 21:31, 6年前 , 4F
留在裡面,剩下應該可以自己推理。
05/27 21:31, 4F

05/27 22:13, 6年前 , 5F
喔喔喔 對喔 原來被多讀了一個換行!!! 感謝大大
05/27 22:13, 5F

05/27 22:14, 6年前 , 6F
我再想想怎把那個鬼換行弄掉
05/27 22:14, 6F
※ 編輯: jojojen (223.141.109.32), 05/27/2018 22:26:35 ※ 編輯: jojojen (223.141.109.32), 05/27/2018 22:47:24
文章代碼(AID): #1R2c0_gT (C_and_CPP)