首页 > 解决方案 > 使用逗号作为多个数字输入的分隔符时出现c语言错误

问题描述

我有这个程序,它让用户输入一个数字列表,然后程序在输入中找到最大的数字,并计算输入最大数字的次数。

当我使用空格作为分隔符时,程序运行良好。但是当我使用逗号作为分隔符时,似乎出现了逻辑错误。

这是我的源代码:

int i, numberOfIntegers, listOfIntegers, largest = 0, occurrence = 0;

printf("\n \t \t \t Finding the LARGEST integer \n");

printf("\n How many integers do you want to enter? ");
scanf("%i", &numberOfIntegers);

printf("\n Input %i list of integers: \n ", numberOfIntegers);

for (i = 1; i <= numberOfIntegers; i++)
{
    printf("\t");
    scanf("%i", &listOfIntegers);

    if (listOfIntegers > largest)
    {
        largest = listOfIntegers;
        occurrence = 1;
    }
    else if (listOfIntegers == largest)
    {
        occurrence++;
    }
}

printf("\n The largest value is %i and the number of occurrence is %i \n ", largest, occurrence);

return 0;

这是我使用逗号作为分隔符的输出示例:

How many integers do you want to enter? 4

Input 4 list of integers:
        5, 6, 6, 6

 The largest value is 5 and the number of occurrence is 4

而正确的输出应该是:

How many integers do you want to enter? 4

Input 4 list of integers:
        5, 6, 6, 6

 The largest value is 6 and the number of occurrence is 3

有人能指出我到底在哪里做错了吗?

标签: cloopsfor-loopif-statementinput

解决方案


基本问题是,在读取 C 中的输入时,您需要考虑输入中的每个字符(可能)——每个空格、每个换行符、每个逗号或其他标点符号,以及您真正关心的所有值和想读。

用于scanf读取输入时,空格很特殊,因为它很容易被忽略。scanf 字符串中除,之外的每个%指令都会自动忽略前导空格。就像您使用的一样,循环中的第一个 scanf 调用会自动忽略(跳过)输入中的换行符,并且以后的调用将跳过数字之间的空格。但是,任何逗号(或其他标点符号)都不会。您需要明确地跳过(阅读)它们。实际上,当您的程序在循环的第二次迭代中调用时,要读取的下一个字符是(不是数字也不是空格),因此转换失败并且没有任何内容存储到%c%[%%"%i"4scanf,listOfIntegers并返回 0(没有匹配的指令)。由于您忽略了 scanf 的返回值,因此您不会注意到这一点并愉快地继续使用第一次迭代留下的相同值。

您可以尝试的一件事是scanf("%i,", &listOfIntegers)在您的循环中。,如果它立即出现在您的号码之后,它将读取一个单曲。如果数字后面的字符不是 a,它将什么也不做。虽然这适用于您的示例,但它不适用于像这样的输入

5 , 6, 6 , 6

由于逗号前有多余的空格。一个更容易接受的可能性是

scanf("%i%*[ \t,;.]", &listOfIntegers)

这将跳过(并忽略)数字后的所有空格、制表符、逗号、分号和句点。

在任何情况下,检查 scanf 的返回值也是一个好主意:

if (scanf("%i%*[ \t,;.]", &listOfIntegers) < 1) {
    ... something is wrong -- the next input is not a number

捕捉某人输入字母或其他非数字输入。


推荐阅读