c – while循环在输入错误后继续忽略scanf
发布时间:2020-12-16 07:17:56 所属栏目:百科 来源:网络整理
导读:我在论坛上搜索了解决方案,但仍然对我的代码产生的输出感到困惑. 所以,该程序非常简单. 它在输入处获得两个数字,直到到达文件末尾. 如果输入错误,则应将错误打印到stdout并继续执行下一对. 如果两者都是素数,它会打印出素数.否则,它会打印他们的GCD. 问题是,
我在论坛上搜索了解决方案,但仍然对我的代码产生的输出感到困惑.
所以,该程序非常简单. 它在输入处获得两个数字,直到到达文件末尾. 问题是,如果输入错误,即一个或两个数字实际上不是数字,程序将跳过scanf并继续向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 inputn"); } else { if (a == 1 || b == 1){ printf("1n"); } else if (nd(a) == 1 && nd(b) == 1){ printf("primen"); } else { printf("%dn",nsd(a,b)); } } } fprintf(stderr,"DONEn"); return 0; } 解决方法
我整理了一个简单的程序来验证返回值:
#include <stdio.h> int main() { int a; int b; int inp_status = 0; inp_status = scanf(" %d %d",&b); printf("INP status: %dn",inp_status); printf("EOF = %dn",EOF); return 0; } 这是该计划的结果: 那是因为这些字母实际上是存储的. #include <stdio.h> int main() { int a; int b; int inp_status = 0; inp_status = scanf(" %d %d",EOF); printf("Values stored: a = %d,b = %dn",a,b); return 0; } 值存储不正确,但程序仍在执行.通过使用scanf存储结果,它们实际上不会导致错误. 验证输入的最有效方法是确保两者都有,就像this solution一样.基本上, if (inp_status != 2){ break; } 代替 if (inp_status == EOF){ break; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |