在 C 编程语言中使用 getchar() 计算字符数以获取输入字符

counting of characters in c programming language using getchar() to get input character

提问人:Devesh from India 提问时间:6/20/2023 最后编辑:Vlad from MoscowDevesh from India 更新时间:6/20/2023 访问量:86

问:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
    
        int num=0,ch='9';
    
        while((ch=getchar())!=EOF){
            ++num;
        }
        printf("\n%d",num);
    }

/* this is a program to count no of characters entered using getchar(). 

假设我输入了

1
2
3
4
5

显示的答案是 10 而不是 5

*/enter image description here

c while-loop char 换行符 getchar

评论

0赞 12431234123412341234123 6/20/2023
你如何定义一个角色?您计算的是字节而不是字符。C 中的 A 与字符无关。这个序列应该算多少个字符?: , ' , (制表符), (换行符), , , , , (请注意,这是 3 个较小的字母组合成 1 个较大的字母。对不起,不知道正确的术语,我不明白韩语),,(请注意,这是多个unicode码位的组合),,... ?当输入不是有效的 unicode(假设为 UTF8)时,它应该怎么做?chara, ,.-?\t\näµ😶🇨🇭
0赞 12431234123412341234123 6/20/2023
这是多少个字符:?1?33(代码点数)?您的程序将计数 62。h̶̢̨͇͓̼̤͎̣̝͖̳̫̋͛̏̑̃́̾̐́͊̆̋͘͘͜͝͝

答:

0赞 Vlad from Moscow 6/20/2023 #1

该函数读取任何字符,包括空格字符,例如,与按下的键 Enter 相对应的换行符,如程序的输出所示getchar'\n'

如果你想跳过空格字符,你可以写,例如

#include <stdio.h>
#include <ctype.h>

int main( void )
{
    size_t num = 0;
    int ch;

    while ( ( ch = getchar() ) != EOF )
    {
        if ( !isspace( ch ) ) ++num;
    }

    printf( "\num = %zu\n", num );
}

如果您只想跳过换行符,那么程序可以按如下方式运行

#include <stdio.h>

int main( void )
{
    size_t num = 0;
    int ch;

    while ( ( ch = getchar() ) != EOF )
    {
        if ( ch != '\n' ) ++num;
    }

    printf( "\num = %zu\n", num );
}

另一种方法是使用另一个标准函数,例如scanf

#include <stdio.h>

int main( void )
{
    size_t num = 0;
    char ch;

    while ( scanf( " %c", &ch ) == 1 )
    {
        ++num;
    }

    printf( "\num = %zu\n", num );
}

注意格式规范中的前导空格

scanf( " %c", &ch )
       ^^^

它允许跳过空格字符。

评论

0赞 Devesh from India 6/20/2023
但是 getchar() 怎么可能接收两个字符,即使有可能,但只取初始值
0赞 Vlad from Moscow 6/20/2023
@DeveshKumar 正如我在答案中所写的,getchar 读取由 you 键入的字符和与按下的键 Enter 相对应的新行字符。当您按 Enter 键时,系统会将换行符“\n”作为任何键入的字符放入输入缓冲区中。
0赞 Devesh from India 6/20/2023
对不起,打扰你...我只是想理解。这意味着对于每个输入,循环重复两次。
0赞 Vlad from Moscow 6/20/2023
@DeveshKumar 循环的重复次数与输入缓冲区中存在字符的次数一样多。按 Enter 键将换行符放入输入缓冲区中。
0赞 12431234123412341234123 6/20/2023
一个角色不一定完全需要 .在 UTF-8 中,字符需要 2 个字符(假设 )。当你想计算字符数时,它会变得非常复杂,你首先必须定义一个字符(这已经很困难了)。charäCHAR_BIT==8