“ return false”被忽略,不返回

问题描述 投票:0回答:1

注:我已经编辑了我的代码,以提供清晰且最少的步骤来重现该错误。我使用C99 standrad编写了以下代码:

#include <stdio.h>
#include <stdbool.h>

bool FillMatrix(int MatrixSize, int Matrix[][10])
{
    int CellValue=0;
    for (int i=0;i<MatrixSize;i++)
    {
        for (int j = 0; j < MatrixSize; j++)
        {
            if (scanf("%d",&CellValue) == 0)//Check if User provided un-integer value
            {
                printf("Error\n");
                return false;//Her's the problem
            }
            else
            {
                Matrix[i][j] = CellValue;
            }
        }
    }
    return true;
}

int main()
{
    int MatrixSize=0;
    scanf("%d",&MatrixSize);
    int FirstMatrix[10][10],SecondMatrix[10][10];
    printf("First:\n");
    if (!FillMatrix(MatrixSize,FirstMatrix)) return 0;
    printf("Second:\n");
    if (!FillMatrix(MatrixSize,SecondMatrix)) return 0;
    printf("Hello");
    return 0;
}

[当我提供1作为第一个输入,然后输入4.5时,我可以在屏幕上看到Error,但也可以看到Second:我的代码有什么问题?在打印Second之前,我已要求验证FillMatrix(...)并未返回false,但无论如何仍会打印出来!

c function return main c99
1个回答
2
投票

如果我正确理解了您的错误,则似乎在输入1时出现错误,该错误成为MatrixSize的值,然后在输入4.5时出现。由于MatrixSize为1,因此您的代码将扫描4以查找第一个矩阵中的值(并且只有值)。该函数将返回true,并且由于未检测到错误,因此将使用第二个矩阵调用FillMatrix。 .5仍然存在于stdin中,这就是产生错误的地方(调用secondMatrix的FillMatrix的第一个scanf)。

您提到的问题只会出现在矩阵的最后一个输入上。避免此问题的一种方法是将输入作为字符串读取,并检查是否可以将其解析为整数。

© www.soinside.com 2019 - 2024. All rights reserved.