【问题标题】:printing "please enter a number" each time I press enter with only alphabet input每次按回车键时打印“请输入一个数字”,只输入字母
【发布时间】:2021-05-13 14:03:53
【问题描述】:

每当用户按下回车键时,我想提示用户“请输入一个数字”。 先看代码:

#include <stdio.h>
#include <stdio.h>
int main()
{
    int a;
    char b, c;
    int flag = 1;
    while (true) {
        flag = 0;

        if (scanf("%d", &a) == 1)
            break;
        scanf("%c", &b); // this is to clear the frontline characters gradually
        // such that number embedded in the input can be read
        // for e.g. aa4, abdk2jsdl etc
    }
    do {
        scanf("%c", &c); // this is to clear the '\n' buffer if number is the last input(4, as4,hdd7 etc)
        // and others if the input was a2ssdf

    } while (c != 10); // where the buffers will be ssdf and '\n' character

    printf("the number is:%d", a);
}

我试图创建一个只使用 scanf 而不使用字符串的输入系统。我知道使用字符串会更容易。输入系统是这样的,除非用户输入一个数字,否则它将不断询问并同时清除所有缓冲区而不使用 fflush,因为它不是标准的。

所以到这里为止一切都很好。但是现在我想添加一个额外的功能来告诉用户“请输入一个数字”,如果用户输入像 aaaaa,dsfk 这样的内容,只有字母。所以,要清楚,我会给出一个 例子...

输入: aaa 输出:请输入一个数字。

第二个输入:hz2 第二个输出:你输入了2。

但我现在能做的是..

上述输入“aaa”的输出:请输入数字请输入数字请输入数字

所以基本上我只想在用户按下回车键时打印它并且只打印一次 你知道吗?它没有使用字符串。

【问题讨论】:

  • 家庭作业?是否需要使用scanf()?为什么不使用读取单个字符的函数,例如getchar()
  • 为什么要两次包含同一个头文件?

标签: c scanf buffer enter


【解决方案1】:

试试这个功能

int getnum() {
    int input;
    int num = 0;
    while(1) {
        if((input = getchar()) == '\n')
            printf("Please input a number\n");
        else if(input >= '0' && input <= '9') {
            do {
                num = num * 10 + input - '0';
            } while((input = getchar()) >= '0' && input <= '9');
            break;
        }
    }
    return num;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2016-08-20
    • 1970-01-01
    相关资源
    最近更新 更多