c - 如何将用户输入限制为预定数量的整数

标签 c scanf

我正在使用 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 个输入。我希望它输出“无效输入”。

最佳答案

你说输入将全部在一行上。所以输入一行到一个字符串并检查它。这会尝试扫描第 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");
}

关于c - 如何将用户输入限制为预定数量的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55314230/

相关文章:

c - scanf和format有关吗?

c - 迭代 int 指针时破坏堆栈

通过 shell-wrapper 脚本将带有空格的命令行参数传递给 C 程序

c - 如何使用 gtkmozembed.h 编译程序

c - 使用 fscanf 读取文件时出错

c - scanf 不等待输入

c - 为什么 C 程序返回一个 int?

c - 为什么是$?调用 system() 后总是 0?

c - 为什么 gets() 不起作用而 scanf() 在这里起作用

c - 编辑字符串(字符数组)复制到输入字符串(scanf 或 fgets.. gets)可能吗?