【问题标题】:array, isdigit function, while loop [duplicate]数组,isdigit 函数,while 循环
【发布时间】:2023-03-16 13:18:01
【问题描述】:

这是我为作业编写的 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]);

}

当用户输入整数以外的内容时,我希望程序要求输入整数。

【问题讨论】:

  • 即使您尝试执行的操作可行,您在while 循环之外还有第二个scanf。由于被测试的条件永远不会改变,你会得到一个无限循环。

标签: c


【解决方案1】:

您需要在获得输入后进行从字符串到数字的转换。我的意思是:先输入,然后检查和转换。

// 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 */

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 2021-01-14
    • 1970-01-01
    • 2020-10-28
    • 2012-02-21
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 2021-07-01
    相关资源
    最近更新 更多