C 编程 - 重复 scanf 直到仅输入数字

标签 c function scanf

我不想做的是检查我的输入是否是数字然后继续,否则打印出错误的格式并要求新的输入。我得到的是无限循环打印“格式错误”

这是我输入数字的函数:

void input_number(int *number)
{

    printf("Number: ");

    if ( scanf("%d", number) == 1 )
        return 0;
    else
    {
        printf("-> Wrong format, try again! <-\n");
        input_number(number); // start over
    }
}

当我运行程序时,我希望它看起来像这样:

号码:你好

-> 格式错误,请重试! <-

数量:4

然后继续......

最佳答案

试试这个:(注意有很多更好的方法可以做到这一点)

void input_number(int *number)
{
    int flag=1;
    printf("Number: ");

    while(flag==1){
        if ( scanf("%d", &number) == 1 ){ // also you were missing & specifier
            flag = 0;
            //return 0;
        }else{
            printf("-> Wrong format, try again! <-\n");
            getchar(); // to catch the enter from the input -- make sure you include stdlib.h

        }
    }

    return 0;
}

输出:

Number: f
-> Wrong format, try again! <-
Number: f
-> Wrong format, try again! <-
Number: d
-> Wrong format, try again! <-
Number: d
-> Wrong format, try again! <-
Number: s
-> Wrong format, try again! <-
Number: s
-> Wrong format, try again! <-
Number: s
-> Wrong format, try again! <-
Number: s
-> Wrong format, try again! <-
Number: 6

关于C 编程 - 重复 scanf 直到仅输入数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19259612/

相关文章:

c++ - 如何知道我的编译器自动完成了哪些优化

c - MS C 编译器要求变量声明位于函数的开头。标准支持吗?

c - 将用户输入存储在变量中

c++ - IP到长转换c++

c++ - 如何使用 CMake 添加编译器参数?

php - 获取 PHP 中最后一个查询的实际(绝对)执行时间(不包括网络延迟等)

javascript - 我对 shuffle 数组函数的设置和调用哪里出了问题?

c++ - C++中的函数与变量声明

c - 如何使用分隔符使用 fscanf 扫描文本文件?

c - 为什么在使用 scanf 读取字符串后整数变量的值会发生变化?