c - 为什么输入字符时循环会陷入无限循环
问题描述
这是一个错误的代码。错误的问题之一是程序在输入字符时会陷入无限循环。请忽略代码中存在的其他错误,只关注字符导致无限循环的问题。
#include <stdio.h>
int main()
{
int x1, x2;
do{
printf("Input x1, x2:");
scanf("%d,%d", &x1, &x2);
}while (x1 * x2 > 0);
printf("x1=%d,x2=%d\n", x1, x2);
return 0;
}
解决方案
输入字符时程序会陷入死循环。
当您没有为scanf %d
错误输入输入有效数字时,不会删除错误输入,因此如果您什么都不做,下一次您将再次得到它scanf %d
一份提案 :
#include <stdio.h>
int main()
{
int x1, x2;
do{
printf("Input x1, x2:");
if (scanf("%d,%d", &x1, &x2) != 2) {
char * lineptr = NULL;
size_t n = 0;
ssize_t r = getline(&lineptr, &n, stdin); /* flush input */
if (r == -1)
/* EOF */
return -1;
free(lineptr);
}
} while (x1 * x2 > 0);
printf("x1=%d,x2=%d\n", x1, x2);
return 0;
}
编译和执行:
/tmp % gcc -pedantic -Wextra c.c
/tmp % ./a.out
Input x1, x2:1,2
Input x1, x2:a
Input x1, x2:1,a
Input x1, x2:1 2
Input x1, x2:0,1
x1=0,x2=1
(编辑)
如果您只想在出现错误时停止循环:
#include <stdio.h>
int main()
{
int x1, x2;
int ok = 1;
do{
printf("Input x1, x2:");
if (scanf("%d,%d", &x1, &x2) != 2) {
ok = 0;
break;
}
} while ((x1 * x2) > 0);
if (ok)
printf("x1=%d,x2=%d\n", x1, x2);
return 0;
}
或在错误时完成所有执行
#include <stdio.h>
int main()
{
int x1, x2;
do{
printf("Input x1, x2:");
if (scanf("%d,%d", &x1, &x2) != 2)
return 0;
} while ((x1 * x2) > 0);
printf("x1=%d,x2=%d\n", x1, x2);
return 0;
}
编译和执行:
/tmp % gcc -pedantic -Wextra c.c
/tmp % ./a.out
Input x1, x2:1,2
Input x1, x2:1,0
x1=1,x2=0
/tmp % ./a.out
Input x1, x2:1,,
/tmp %
推荐阅读
- mysql - Mysql Foreach 从一个表到另一个表第 2 部分
- spring-boot - JPA 的 deleteAll 在表中留下一个条目。我怎样才能清楚地删除所有条目?
- node.js - 机器人框架 continueDialog 没有弹出堆栈
- ios - Xcode 更新后如何修复 Core NFC 框架的无效授权
- youtube - 为什么 Google 不为其产品(如 google.com、youtube.com)使用 PWA 功能
- javascript - 使用对象过滤对象数组驻留在嵌套数组属性中
- asp.net-core - 升级到 ASP.NET Core 3.0 后,我得到“无法创建 stdoutLogFile 错误代码 = -2147024893”。
- powerbi - 是否有一个公式可以自动将数据从多列拖到新列中?
- arrays - 按类型对结构数组进行排序,然后按另一个属性按字母顺序排序
- android - 本地网络上的 Youtube Cast 按钮 Android