[英]c - while loop keeps ignoring scanf after bad input
我在論壇上搜索了解決方案,但仍然對我的代碼產生的輸出感到困惑。
所以,該程序非常簡單。
它在輸入處獲得兩個數字,直到到達文件末尾。
如果輸入錯誤,則應將錯誤打印到stdout並繼續執行下一對。
如果兩者都是素數,它會打印出prime
。 否則,它會打印他們的GCD。
問題是,如果輸入不好,即一個或兩個數字實際上都不是數字,程序會跳過scanf並繼續向stderr打印錯誤。
然而,在調試期間,我發現scanf()
所有下一次迭代都經過,它返回0
,好像根本沒有輸入任何內容。
並且提示對於輸入無效,因為程序不斷打印到stderr。
nd
和nsd
分別是返回最大分頻器和最大公約數的函數。
主要計划如下:
#include <stdio.h>
#include "nd.h"
#include "nsd.h"
int main()
{
int a;
int b;
int inp_status = 0;
while (1){
inp_status=scanf(" %d %d", &a, &b);
if (inp_status == EOF){
break;
} else if (inp_status < 2){
fprintf(stderr, "Error: bad input\n");
} else {
if (a == 1 || b == 1){
printf("1\n");
} else if (nd(a) == 1 && nd(b) == 1){
printf("prime\n");
} else {
printf("%d\n",nsd(a,b));
}
}
}
fprintf(stderr, "DONE\n");
return 0;
}
我整理了一個簡單的程序來驗證返回值:
#include <stdio.h>
int main()
{
int a;
int b;
int inp_status = 0;
inp_status = scanf(" %d %d", &a, &b);
printf("INP status: %d\n", inp_status);
printf("EOF = %d\n", EOF);
return 0;
}
那是因為這些字母實際上是存儲的。
#include <stdio.h>
int main()
{
int a;
int b;
int inp_status = 0;
inp_status = scanf(" %d %d", &a, &b);
printf("INP status: %d\n", inp_status);
printf("EOF = %d\n", EOF);
printf("Values stored: a = %d, b = %d\n", a, b);
return 0;
}
值存儲不正確,但程序仍在執行。 通過使用scanf存儲結果,它們實際上不會導致錯誤。
驗證輸入的最有效方法是確保您同時擁有這兩種方法,就像使用此解決方案一樣 。 基本上,
if (inp_status != 2){
break;
}
代替
if (inp_status == EOF){
break;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.