c - isdigit 和 scanf 具有无限循环

标签 c

我的程序出了什么问题?当我第一次输入数字时,它会在 if 中打印语句,但是当我退出程序并使用 char 重新输入时,它会在 else 中打印语句,并且当我继续输入数字时循环永远不会退出。

#include <stdio.h>
#include <ctype.h>
int main()
{
    int x;
    char y;
    for(x=0;x<4;x++)
    {
            puts("Please enter a number:");
            scanf("%c",&y);
            if(isdigit(y))
            {
                    printf("Y is a digit!\n");
                    break;
            }
            else
            {
                    printf("Y is not a number, please enter another number:\n");
                    scanf("%d",&y);
            }
    }
    return 0;

}

最佳答案

我认为您的程序中有一个错误,特别是在 else 部分。您使用了 scanf("%d",&y); 而不是 scanf("%c",&y);

%d 用于整数,但 y 的声明是 char,因此必须使用 %c

关于c - isdigit 和 scanf 具有无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27392326/

相关文章:

c - 读取 mini-XML 2.7 中的多行字段时出现问题

c - 失败注入(inject) :Try to write into protected RAM area

c - 不使用 fopen() 逐行读取 txt 文件

c - strtok 及其用法

c - 数独生成器导致段错误

java - 计算平均值的简单数学公式

c - 如何从ARM中的32位端口的第15脚获取值?

C - 如何保护变量在函数中的某个点后不被意外更改

c - 函数返回局部变量的地址 [-Wreturn-local-addr]

c - 替换 C 中的字符