当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Function to validate a value returns true when it calls 1 digit, but when its 2 or more it returns false even when it's true

问题描述:

So I have been at this problem for a few hours now and I have no idea what's wrong. This function returns true or false if the int that is called is a valid one. When I call a valid number that is 1 digit long so "0", or "1" it returns true. But when I call a number that is bigger than 1 digit like "83" or "955" which should return true, it always returns false even when it should return true!

My validator function:

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;

and the code that calls that function:

 for ( i = 0; i < areaCounter; i++)

{

cout << areaInt << endl;

areaCheck = isRegistered(file, areaInt);

if (areaCheck != 1)

areaInt = areaInt * 10 + areaIntA[i+1];

}

If the value of areaIntA[3] = 955, then the loop calls, 9, then 95, then 955 until it no longer has digits to call. 955 SHOULD return true because that value is true but for some reason it is returning false.

When I call '0' or '1' which are true, it returns true but for anything larger than 1 digit it always returns false. Anyone know why?

网友答案:

The function isRegistered reads the file to its end, and you never rewind it. The first call to isRegistered works OK, but the next ones never enter the while loop because fscanf returns EOF.

If isRegistered is meant to search the whole file, try this:

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;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: