Jeremy Stubbert
Jeremy Stubbert

Reputation: 5

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.

Upvotes: 0

Views: 85

Answers (2)

chqrlie
chqrlie

Reputation: 144969

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;

Upvotes: 1

Xenon
Xenon

Reputation: 304

indice2 is incremented before it is compared so you are not comparing against read value but index after that I believe.

Upvotes: 2

Related Questions