首页 > 解决方案 > 如何将用户输入限制为预定数量的整数

问题描述

我正在使用 scanf (带有循环)将整数分配到数组中。我希望用户只在终端中输入 8 个整数(它将在一行上)。如果他们输入 9 个数字,我希望程序打印一条错误消息。

我试图将 if 语句与 scanf 结合起来。

int main(){
int input[8] = {0};
int countM = 0;

while(countM < 9){
    if(scanf("%d", &input[countM]) < 8){
        countM++;
    } else{
        printf("Invalid input");
        exit(0);
    }
}
return(0);
}

它没有检测到第 9 个输入。我希望它输出“无效输入”。

标签: cscanf

解决方案


您说输入将全部集中在一行上。因此,在字符串中输入一行并检查一下。这会尝试扫描第 9 个输入。

int input[8] = { 0 };
char dummy[8];
char buff[200];
if(fgets(buff, sizeof buff, stdin) == NULL) {
    exit(1);                // or other action
}
int res = sscanf(buff, "%d%d%d%d%d%d%d%d%7s", &input[0], /* etc */, &input[7], dummy);
if(res != 8) {
    exit(1);                // incorrect inputs
}

这是一个完整的工作示例,从 @AnttiHaapala 评论改进并减少以接受两个数字而不是 8。

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

int main(void) {
    int input[2] = { 0 };
    char dummy;
    char buff[200];
    if(fgets(buff, sizeof buff, stdin) == NULL) {
        exit(1);                // or other action
    }
    int res = sscanf(buff, "%d%d %c", &input[0], &input[1], &dummy);
    if(res != 2) {
        exit(1);                // incorrect inputs
    }
    puts("Good");
}

推荐阅读