首页 文章

验证值的函数在调用1位数时返回true,但是当它为2或更多时,它返回false,即使它是真的

提问于
浏览
0

所以我现在已经解决了这个问题几个小时了,我不知道出了什么问题 . 如果调用的int是有效的int,则此函数返回true或false . 当我调用长度为1位的有效数字为“0”或“1”时,它返回true . 但是当我调用一个大于1位的数字时,如“83”或“955”应该返回true,它总是返回false,即使它应该返回true!

我的验证函数:

int isRegistered(FILE* file, int area) {

int areaDigit = 0;
int check = 0;

while(fscanf(file, "%d %*[^ ] %*[^\n]", &areaDigit) != EOF)
{
     if (area == areaDigit)
       check = 1;
}

return check;

以及调用该函数的代码:

for ( i = 0; i < areaCounter; i++)
    {
    cout << areaInt << endl;
    areaCheck = isRegistered(file, areaInt);

    if (areaCheck != 1)
        areaInt = areaInt * 10 + areaIntA[i+1];
    }

如果areaIntA [3] = 955的值,则循环调用9,然后是95,然后是955,直到它不再有要调用的数字 . 955应该返回true,因为该值为true但由于某种原因它返回false .

当我将'0'或'1'称为真时,它返回true,但对于任何大于1位的数字,它总是返回false . 谁知道为什么?

1 回答

  • 2

    函数 isRegistered 将文件读取到它的结尾,你永远不会回卷它 . 第一次调用 isRegistered 工作正常,但是下一个调用从不进入 while 循环,因为 fscanf 返回EOF .

    如果 isRegistered 用于搜索整个文件,请尝试以下操作:

    int isRegistered (FILE * file, int area)
    {
        int areaDigit = 0;
    
        rewind (file);  // Go to beginning of file and clear flags
    
        while (fscanf (file, "%d %*[^ ] %*[^\n]", &areaDigit) != EOF)
            if (area == areaDigit)
                return 1;
    
        return 0;
    }
    

相关问题