看板 C_and_CPP 關於我們 聯絡資訊
我想你要的是:讓使用者決定資料輸入完沒.. 比較簡單的方式是類似以下方法: int sum = 0; int cnt = 0; printf("please input a integer:(-1 to exit.)"); while(scanf("%d", &data)){ if(data == -1) break; sum = sum + data; cnt++; printf("please input a integer:(-1 to exit.)"); } printf("input times:%d\n", cnt); printf("sum : %d\n", sum); 一般加上輸入錯誤機制的話可能會長得像這樣 int temp = 0; int ret = 0; int sum = 0; int cnt = 0; while(true){ printf("please input a integer(-1 to exit):"); ret = scanf("%d",&temp); if(ret==0) { printf("輸入錯誤!!請重新輸入\n"); } else if(temp!=-1){ cnt++; sum+=temp; } else{ printf("輸入結束!!\n"); break; } } printf("輸入次數:%d\n", cnt); printf("輸入數字總合:%d\n", sum); // ======================================= code 有點醜.. 但可參考.. ※ 引述《tropical72 (藍影)》之銘言: : scnaf 回傳值是 "引數成功 match 之數目" : ex: : int a1, a2, a3; : int ret = scanf("%d%d%d", &a1, &a2, &a3); : 如果使用者輸入 10 22 12 : 回傳值 ret = 3 : 如果值用者輸入 10 22 ss : 最後一個引數沒有 match 到 : 回傳值 ret = 2 : 以您的例子 while(scanf("%d", &num) {....} : 事實上可以看成 : while(scanf("%d", &nun)!=0) {....} : 或是 : while(scanf("%d", &num)==1) {....} : 是一樣的意思, : 只要輸入不是正常的整數, 這個迴圈就會停下來 : 參考.. : ※ 引述《gsrr (下象棋)》之銘言: : : while (scanf("%d",&num)) : : { : : ... : : } : : 像上述狀況,以scanf進行輸入時, : : 若輸入 22 33 44,時會依序讀入22,33,44 : : 請問一下此時如何判斷說讀取時為輸入的最後一個數字. : : 謝謝! -- 我期待 我等待 肩狹骨上的翅膀早些長出來 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 180.177.77.80
tropical72:while(scanf("%s",String))!=0) { 05/09 23:11
tropical72: if(!strcmp(String, "END")) break; 05/09 23:12
tropical72: else {int data = atoi(String); ...} } 05/09 23:12
tropical72:當然應該還用不到這種方式.. 05/09 23:13
※ 編輯: tropical72 來自: 180.177.77.80 (05/09 23:22) ※ 編輯: tropical72 來自: 180.177.77.80 (05/09 23:23)
tinlans:老實說,我很好奇,輸入的不是數字時會不會變成無窮迴圈。 05/10 00:11
tinlans:看錯了,輸入錯誤不會進去 loop... XD 05/10 00:12