【问题标题】:How do I check for extra inputs in scanf in C?如何在 C 中检查 scanf 中的额外输入?
【发布时间】:2021-05-02 01:04:03
【问题描述】:

我正在使用scanf() 获取 x 的值,并且我想检查是否输入了单个整数以外的任何内容;如果是,我想重新输入。

这是我目前拥有的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char const *argv[])
{
    int x;
    char c;

    int input = scanf("%i%c", &x, &c);

    while (input != 2 || c != '\n')
    {
        input = scanf("%i%c", &x, &c);
    }

    printf("x = %i\n", x);
}

目前,当我输入两个用空格分隔的整数时,例如23 43,程序会打印出 43,而不是再次要求输入。

任何帮助将不胜感激。

谢谢。

【问题讨论】:

    标签: c scanf


    【解决方案1】:

    考虑使用strtol() 检查字符串中的所有字符是否都已转换为数字。使用fgets 或任何其他行阅读器读取字符串并从中提取数字:

    char buffer[4096];
    fgets(buffer, sizeof(buffer), stdin);
    char *endptr;
    long result = strtol(buffer, &endptr, 10);
    if(*endptr != '\0') { /* There is more input! */ }
    

    作为奖励,您可以读取非十进制数字并检查输入的数字是否在可接受的范围内。

    【讨论】:

    • 是否可以在没有 long int 的情况下做到这一点?
    • 如果需要,您可以将结果转换为 intint result = (int)strtol...
    【解决方案2】:

    您需要以其他方式执行此操作,因为 int 只允许单个数字示例:1000 您可以执行以下操作:1000 2000 但是还有另一种方式可以询问用户他要输入的数字计数,然后为 scanf 循环对于数字的计数,您可以在这里做任何您想做的事情:

    #include <stdio.h>
    
    int main()
    {
        int loopTime = 0;
        int temp = 0;
        int result = 0;
    
        printf("Enter the count of number you need to enter: ");//the number of times scanf going to loop
        scanf("%d", &loopTime);
    
        printf("Now enter the numbers you going to store but after every number you need to press enter\n");
    
        for (int i = 0; i < loopTime; i++)
        {
            scanf("%d", &temp);
            result += temp;
        }
    
        printf("The Result is: %i", result);
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-23
      • 2018-08-22
      • 2023-03-18
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 2019-02-23
      相关资源
      最近更新 更多