简体   繁体   中英

Why is my fscanf not working?

For some reason I have no idea why, my fscanf code does not work. My friend with the same assignment and the same code works for him.

ISBNPrefix::ISBNPrefix(const char * filename) {
    FILE * prefixFile = NULL;

    if (filename != NULL)
    prefixFile = fopen(filename, "r");
}

bool ISBNPrefix::isRegistered (int area) const {
    int areaDigit = 0;
    bool check = false;

    //rewind(prefixFile);

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

    return check;
}

It does not fscanf properly, it should return true on some tests but it returns false; I don't think it's scanning properly. Can anyone see what's wrong?

The first four lines of my text file are:

0 00 19
0 200 699
0 7000 8499
0 85000 89999

This line:

while(fscanf(prefixFile, "%d %*[^ ] %*[^\n]", &areaDigit) != EOF) {

will

  • read a number into areaDigit, then
  • skip whitespace in the input, then
  • read one or more non-space characters, then
  • skip whitespace again, then
  • read and discard all characters up to the next newline.

Should it get to the end of the file BEFORE reading the number for areaDigit , the loop will end. So for example with an input like:

123 456 789
555 xxx yyy

it will loop twice with areaDigit as 123 and 555

With an input like:

1 2 3 4 5 6 7 8 9
a b c d e f g h i

it will read 1 and then go into an infinite loop failing to read the second line (with areaDigit == 1 the whole time.)

With an input like:

1
2
3
4
5
6
7

it will loop 3 times with areaDigit as 1, 4, and 7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM