【问题标题】:How to limit user input to a predetermined number of integers如何将用户输入限制为预定数量的整数
【发布时间】:2019-03-23 13:31:51
【问题描述】:

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

【问题讨论】:

  • 如果您只想读取 8 个整数,请不要尝试将第 9 个整数读入input[countM],因为这会导致未定义的行为(尝试访问input[8])。先尝试读取一个整数,然后只有在成功的情况下,才将其放入数组并增加计数。正如@xing 所指出的,请查看scanf 的手册页。返回值指示读取了多少值或 EOF。与 8 的比较在这里毫无意义。

标签: c scanf


【解决方案1】:

您说输入将全部在一行上。因此,在字符串中输入一行并检查它。这会尝试扫描第 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");
}

【讨论】:

  • 为什么随机%7s?只需使用" %c" 就足够了
  • @AnttiHaapala 我同意,那会奏效的。我原本打算使用另一个%d,但添加了一个更好的方法。
【解决方案2】:

让我们看看你的代码。

int input[8] = {0};                     // (1)
int countM = 0;
while(countM < 9){
    if(scanf("%d", &input[countM]) < 8) // (2)
    ...
}

在 (1) 中,您定义了一个长度为 8 的数组。在 (2) 中,您有一个遍历 9 个整数(从 0 到 8)的 while 循环。在循环的最后一次运行期间,你有相当于

scanf("%d", &input[8] < 8)

超出数组范围。越界,就有龙。此外,&lt; 8 比较并没有达到您想要的效果。

如果您打算检查边界,您应该在访问或分配数组的该部分之前这样做。

例如:

while(countM < 9){
    if (countM > 7)
    {
        // do whatever you want when this should happen
        break;
    }
    // rest of code
}

但是正如你所看到的,这有点奇怪。你知道你会触发那个代码。

你可以用类似的东西做得更好

int val;
int countM = 0;
while (scanf("%d", &val) == 1)
{
    if (countM > 7)
    {
        printf("Whoops");
        // whatever you want
        exit(1);
    }
    // rest of code
}

【讨论】:

  • @chux 当然,你是对的。我将编辑我的答案。
猜你喜欢
  • 1970-01-01
  • 2019-12-24
  • 1970-01-01
  • 2014-11-07
  • 2018-01-26
  • 2022-11-03
  • 1970-01-01
  • 2020-08-24
相关资源
最近更新 更多