简体   繁体   中英

While loop doesn't stop after reading '\n'

int lire(int indice1) {
    int indice2 = 0;
    char c[1000];
    FILE *fptr;
    FILE *indice2r;
    indice1 = 0;
    fptr = fopen("Participant.txt", "r");
    if (fscanf(fptr, "%d", &indice1) == EOF) {
        return (indice1);
    } else {
        while (fscanf(fptr, "%d", &indice1) != EOF) {
            indice2r = fopen("indice2.txt", "w+");
            fscanf(indice2r, "%d", &indice2);
            for (indice2 = 0; c[indice2] != '\n'; indice2++) {
                fscanf(fptr, "%c", &c[indice2]);
            }
            fscanf(fptr, "%d", &indice1);
            indice1++;
            fprintf(indice2r, "%d", indice2);
        }
        fclose(indice2r);
        return indice1;
    }
}

My problem is that whenever my program goes into the for function that is supposed to stop after reading '\\n' it keeps going and doesn't leave the loop.

indice2在进行比较之前就已递增,因此您相信不是在与读取值进行比较,而是在索引之后进行比较。

Do not compare the return value of fscanf() to EOF , instead compare to the expected number of conversions.

Furthermore, there is a major confusion in this code:

        fscanf(indice2r, "%d", &indice2)
        for (indice2 = 0; c[indice2] != '\n'; indice2++) {
            fscanf(fptr, "%c", &c[indice2]);
        }

You read an integer into indice2 , then use the same variable to scan for the end of line. You should use a different approach to skipping to the end of line:

        if (fscanf(indice2r, "%d", &indice2) != 1) {
            /* handle invalid input... */
        }
        /* consume the end of the line */
        int c;
        while ((c = getc(indice2_r)) != EOF && c != '\n')
            continue;

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