My C program counts characters incorrectly

a 夏天 提交于 2019-12-11 04:49:54

问题


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? :/


回答1:


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


来源:https://stackoverflow.com/questions/37659350/my-c-program-counts-characters-incorrectly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!