user1895783
user1895783

Reputation: 381

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?

Upvotes: 0

Views: 311

Answers (1)

comocomocomocomo
comocomocomocomo

Reputation: 4942

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;
}

Upvotes: 2

Related Questions