这是我为作业编写的 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]);
//if tab1[c] is not a number ask again.
while (!isalpha(tab1[c]))
{
printf("nEnter an integer : ");
}
scanf("%d",&tab1[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 */
关于c - 数组、isdigit 函数、while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55765417/