简体   繁体   中英

How do I get number of characters in each line?

I need to get number of characters in each line and then paste it into another file (school project) but even my prototype is already not working.

I have already trying continuing seeing whether problem resolves itself when I paste it into another file but it didn't work so I'm back to this.

int main()
{
    FILE *fw;
    FILE *fr;
    int i = 0;
    char c;
    fr = fopen("vstup.txt","r");
    fw = fopen("vystup.txt","w");
    while ((c = getc(fr)) != EOF)
    {
        while ((c = getc(fr)) != '\n')
        {
            i++;
        }
        printf("%d\n", i);
    }
}

c has to be declared int , not char . EOF might not be a valid char value, so the inequality might succeed forever.

You shouldn't call getc() twice. You never check the result of the first call to see if it's a newline.

You need to set i back to 0 after you read a newline, otherwise you'll keep adding the next line's length to the previous line.

You should only print the length when you read a newline, not every time through the loop. And if the last line doesn't end with newline, you should print its length after the loop; you can tell this happened if i is not 0 when it's done.

Since the lengths should be written into the other file, you should use fprintf() .

while ((c=getc(fr)) != EOF) {
    if (c == '\n') {
        printf("%d\n", i);
        i = 0;
    } else {
        i++;
    }
}
if (i != 0) {
    fprintf(fw, "%d\n", i);
}

You don't need a nested loop. You need to zero out the counter either way, so you may as well just use an if instead of a while:

int main()
{
    FILE *fw, *fr;
    int count = 0;
    int c;

    fr = fopen("vstup.txt","r");
    fw = fopen("vystup.txt","w");

    while ((c = getc(fr)) != EOF) {
        count++;
        if(c == '\n') {
            fprintf(fw, "%d\n", count);
            count = 0;
        }
    }

    fclose(fr);
    fclose(fw);
}

This version will count newlines as valid characters.

Note that c must be an int , not a char , so that it can hold every character value returned by getc as well as EOF , which is not a character value.

And don't forget to close your files!

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