c - 检测是否只给出整数的程序进入无限循环
问题描述
// program to detect whether only integer has been given or not
int main() {
int a, b, s;
printf("Enter two proper number\n");
BEGIN:
s = scanf("%d %d", &a, &b); //storing the scanf return value in s
if (s != 2) {
printf("enter proper value\n");
goto BEGIN;
}
printf("The values are %d and %d ", a, b);
}
当输入无效数据而不是询问新值时,这个检测是否只给出整数的程序进入无限循环为什么在goto
这里不起作用?
解决方案
请注意,当scanf
输入错误(例如您输入cat dog)时,该输入将保留在输入缓冲区中,直到您采取措施将其清除。所以循环不断重复并拒绝仍然存在的相同输入。
它使用起来更简单fgets
,sscanf
如果扫描失败,您只需忘记输入字符串并获取另一个字符串。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a, b;
char str[42];
do {
printf("Enter 2 numeric values\n");
if(fgets(str, sizeof str, stdin) == NULL) {
exit(1);
}
} while(sscanf(str, "%d%d", &a, &b) != 2);
printf("Numbers are %d and %d\n", a, b);
}
节目环节:
输入 2 个数值 猫狗 输入 2 个数值 猫 43 输入 2 个数值 42 狗 输入 2 个数值 42 43 数字是 42 和 43
请注意,这goto
是 C 语言中不好的做法,仅应在没有其他方式构建代码的情况下使用——通常有这种方式。
推荐阅读
- ios - 如何存储 [[string]] 并从核心数据中获取它?
- docker - 为什么“sh -c 命令”中的 -c 在某些情况下是强制性的,而在其他情况下是不允许的?
- json - 如何从 OPENJSON 获取多列值并交叉应用
- javascript - 使用 Nativescript + Angular 实现与 SignalR 的连接
- dart - 为什么我的自定义随机课程无法生成随机数,而标准数学课程却可以,魔法发生在哪里?
- ios - 如何为 ios 应用描述添加其他语言的本地化
- python - 在 Python 中输出二进制序列的最佳方法
- sql - 如何存储计划时间块并对其进行查询?
- nginx - 用于安全服务间通信的信任自签名 SSL/TLS 证书
- ios - PDFKit - PDFDocument 对象在保存时增加文件大小