Home > Blockchain >  Read the length of 5 strings in file
Read the length of 5 strings in file

Time:12-08

Hello guys I have this question for code C: Read the input data(input02.txt) contain 5 strings, then write to new file the length of each string. Strings in file:

Five little
Monkeys jumping
On the bed
One fell off
And bumped his head

Here is my code:

#include <stdio.h>
#include <string.h>

int main(){
    char s[100];
    int m,c=1;
    FILE *fin,*fout;
    fin = fopen("input02.txt", "r");
    fout = fopen("length.txt", "w");
    if (fin!=NULL){
        while(!feof(fin)){ 
            fgets(s, 100, fin);
            m=strlen(s);
            while(c<6){
                fprintf(fout,"Length of %d string: %d\n",c,m);
                c  ;
            }
        }
        fclose(fin);
        fclose(fout);
    }
    return 0;
}

But the output in the length.txt file show like this:

Length of 1 string: 12
Length of 2 string: 12
Length of 3 string: 12
Length of 4 string: 12
Length of 5 string: 12

Can I get some help, ty

CodePudding user response:

Consider this loop:

while(c<6){
    fprintf(fout,"Length of %d string: %d\n",c,m);
    c  ;
}

It will keep printing and incrementing c without changing the value of m, which is only set in the outer loop. Change the while to if to fix it, assuming you still need to limit the number of strings printed to the first 5. (A more general program would just read whatever is in the file, in which case the condition is not needed.)

(The comment you received about not using feof as the loop condition is still valid; also fix that, although it was not directly related to this bug.)

CodePudding user response:

It is unclear what you want to achieve with this inner loop.

            while(c<6){
                fprintf(fout,"Length of %d string: %d\n",c,m);
                c  ;
            }

It will print the length of the same string 6 times.

In the next cycle of the outer loop that reads the input lines, the value of c will already be 6, so the inner loop will not be called again for the 2nd or later input lines.


Removing the inner loop will fix the problem

        while(!feof(fin)){ 
            fgets(s, 100, fin);
            m=strlen(s);
            fprintf(fout,"Length of %d string: %d\n",c,m);
            c  ;
        }

In addition to this, a loop like this

    while(!feof(fin)){ 
        /* ... */
    }

is always wrong because feof will tell you if EOF is reached after doing some input operation.

As already mentioned in a comment, a correct loop implementation is

        while(fgets(s, sizeof s, fin)) {
            m=strlen(s);
            fprintf(fout,"Length of %d string: %d\n",c,m);
            c  ;
        }
  • Related