c - 如何将用户输入限制为预定数量的整数
问题描述
我正在使用 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");
}
推荐阅读
- ionic-framework - ionic 5 - 仅当用户按下输入/确认搜索时,如何使用离子搜索栏在服务器上搜索
- discord - 不和谐.JS | 检查频道是否存在票务机器人
- angular - 如果检查,有没有更好的方法来删除这个打字稿代码?
- android-studio - 如何识别 IntelliJ 或 Android Studio 中的函数调用和类实例化?
- powershell - 如何在一段时间内没有输出时杀死/停止powershell进程
- python - 单独文件中的 Python 函数:它们都需要相同的参数。如何在多个文件中创建全局变量?
- javascript - 通过 mongoose 将条目推送到 MongoDB 中的多级嵌套数组
- r - 为什么我没有使用 ggplot2 获得两个图例?
- flutter - 颤振项目无法在视觉工作室中运行
- javascript - 自动完成源响应