我的C程序错误地计算了字符 [英] My C program counts characters incorrectly

查看:62
本文介绍了我的C程序错误地计算了字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,所以我写了一些代码,该代码应该计算用户在控制台中键入的字符,使用getchar()和while循环,直到键入EOF字符为止,但这会增加 count 应该的变量。例如,我输入3个字符,然后输入EOF字符(在本例中为'z'),最后输出我输入了6个字符,如果我输入4个字符+'z',则表示8,如果5则表示10

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

推荐答案

每次使用getchar()输入字符,然后按 enter,再输入一个char这是换行符。

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++;
}

这将解决您的问题。

我已经对您和我的代码进行了一些测试,只是看是否是问题所在。输出在这里:

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

使用您的代码输出:

Hello:
a
s
d
df
You entered 9 charaters.

Hello:
asdf

You entered 5 charaters.

输出带有我的代码:

Hello:
a
s
d
f
You entered 4 charaters

这篇关于我的C程序错误地计算了字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆