gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:11:29 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com