Bruno Filip
Bruno Filip

Reputation: 139

My C program counts characters incorrectly

Hy everyone, so I wrote some code that should count characters that are typed in console by user, using getchar() and a while loop until EOF character is typed, but it adds more to the count variable that it should. For example, I enter 3 characters, and then EOF character(in this case 'z') and at the end It outputs that I entered 6 characters, if I enter 4 chars + 'z' it says 8, if 5 it says 10. It displays x2 number of charaters it should.

#include <stdio.h>
#define END 'z'

int main()
{
    printf("Hello:\n");
    int count = 0;
    int c;

    while ((c = getchar()) != END)
    {
        count++;
    }

    printf("You entered %d charaters.", count);
}

Why is that so? :/

Upvotes: 1

Views: 664

Answers (1)

TeaNyan
TeaNyan

Reputation: 5079

Every time you enter a character with getchar() and after that press "enter", you enter one more char which is a newline character.

while ((c = getchar()) != EOF)
{
    if (c=='\n')
        continue;
    count++;
}

This will solve your problem.

I have done some tests with your and my code, just to see if that was the problem. The output is here:

output with your code:

Hello:
a
s
d
df
You entered 9 charaters.

Hello:
asdf

You entered 5 charaters.

output with my code:

Hello:
a
s
d
f
You entered 4 charaters

Upvotes: 4

Related Questions