C 数组,isdigit函数,while循环
这是我为一项作业编写的C程序。我只想添加一些我自己的代码行。但它最终陷入了一个永无止境的循环 我尝试使用while循环来解决这个问题,但这就是我的问题所在C 数组,isdigit函数,while循环,c,C,这是我为一项作业编写的C程序。我只想添加一些我自己的代码行。但它最终陷入了一个永无止境的循环 我尝试使用while循环来解决这个问题,但这就是我的问题所在 int tab1[6],c; printf("\n\nEnter 4 integers in the first array:\n "); for (c = 0; c < 4; ++c) { printf("\n\tValue %d : ",c+1); scanf("%d",&tab1[c]);
int tab1[6],c;
printf("\n\nEnter 4 integers in the first array:\n ");
for (c = 0; c < 4; ++c)
{
printf("\n\tValue %d : ",c+1);
scanf("%d",&tab1[c]);
//if tab1[c] is not a number ask again.
while (!isalpha(tab1[c]))
{
printf("nEnter an integer : ");
}
scanf("%d",&tab1[c]);
}
int tab1[6],c;
printf(“\n\n在第一个数组中输入4个整数:\n”);
对于(c=0;c<4;++c)
{
printf(“\n\t值%d:”,c+1);
scanf(“%d”和表1[c]);
//如果tab1[c]不是数字,请再次询问。
而(!isalpha(表1[c]))
{
printf(“输入一个整数:”);
}
scanf(“%d”和表1[c]);
}
我想让程序在用户输入非整数时请求输入整数。在获得输入后,您需要进行从字符串到数字的转换。我的意思是:首先输入,然后检查和转换
// 1st: input
if (!fgets(buf, sizeof buf, stdin)) /* error */;
// 2nd: check and convert
if (sscanf(buf, "%d", &tab1[c]) != 1) /* error */;
scanf()
您希望使用scanf()
的返回值来了解它是否成功转换:
if (scanf("%d", &tab1[c]) != 1) /* error */
即使您尝试执行的操作可行,第二个scanf
也在while
循环之外。因为被测试的条件永远不会改变,所以会得到一个无限循环。