Doubt about accounting for ' n' in C

Asked

Viewed 40 times

2

I have to count the number of characters and line breaks in my file.I did it this way:

The idea is to count the line break every time someone gives enter, but I can only use the getc.

include <stdio.h>
include <stdlib.h>

int main(void) {
    int cont = 0;
    int contlinha = 0;
    while (getc(stdin) != EOF) {
        cont++;
        if (getc(stdin) == '\n') {
            contlinha++;
        }
    }
    printf("Caracteres: %d new lines: %d\n", cont, contlinha);
    system("pause");
    return 0;
}

However this code returns me wrong numbers, and on top of that Z does not come out directly when I open in cmd. What’s wrong? I can’t see what doesn’t work.

1 answer

3


You are reading twice. Use getc only in while and save the result in a variable. Inside the test loop this variable.

include < stdio.h >
include< stdlib.h >

int main(void) {
    int cont = 0;
    int contlinha = 0;
     int c;
    while ((c = getc(stdin)) != EOF) {
        cont++;
        if (c == '\n') {
            contlinha++;
        }
    }
    printf("Caracteres: %d new lines: %d\n", cont, contlinha);
    system("pause");
    return 0;
}
  • can you answer my question? https://answall.com/questions/469237/identificar-registrations-sequentialof each user

Browser other questions tagged

You are not signed in. Login or sign up in order to post.