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

作者: jojojen (JJJ)   2018-05-27 15:37:31
開發平台(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);
希望其他新手不要跟我一樣傻....
作者: kaneson (Lance)   2018-05-27 21:31:00
鍵盤輸入的整行字會先放到buffer,如果裡面還有剩, input相關函數優先從這buffer抓取。如果buffer 內容不足才會發生等待鍵盤輸入。前面scanf讀走了一個%d,至少還有個\n留在裡面,剩下應該可以自己推理。
作者: jojojen (JJJ)   2018-05-27 22:13:00
喔喔喔 對喔 原來被多讀了一個換行!!! 感謝大大我再想想怎把那個鬼換行弄掉

Links booklink

Contact Us: admin [ a t ] ucptt.com