c - 数组、isdigit 函数、while 循环

标签 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]);
        //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/

相关文章:

c - 帮助我的 c shell 中的管道正常工作

c - fork() 进程如何工作(操作系统)

c - openssl 无法让 ENGINE_by_id() 工作

c - C 中的完美数

c - 返回指向指针数组的指针

java - Linux 上 C 与 Java 的接口(interface)

c - 用于频繁随机访问的数组或链表?

c - NULL 宏什么时候不是 0?

C:奇怪的 printf 行为

c - 如何使我的代码符合 MISRA 2012 规则 2.1