C语言,getchar()使用时遇到的问题

C语言,getchar()使用时遇到的问题

【练习3-4】:统计字符:输入1个正整数n,再输入n个字符,统计其中英文字母、空格或回车、数字字符和其他字符的个数。

问题描述:统计回车字符时出现问题,经测试,发现问题,在输入n并敲下回车时,把回车作为了10个需要统计的字符的第一个字符。在第13行添加getchar(),此时,读入了输入,但是getchar()没有赋值给变量,读入的换行符(回车)相当于舍弃了,相当于没有调用。

回车:'\n'

空格:' '

#include <stdio.h>
int main()
{
    int n;
    char ch;
    int letter = 0;
    int digit = 0;
    int space = 0;
    int enter = 0;
    int other = 0;
    printf("Enter n");
    scanf("%d",&n);
    getchar();/*读入并舍弃换行符*/
    printf("Enter %d characters:",n);

    for(int i=1;i<=n;i++){
        ch = getchar();
        if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')){
            letter++;
        }else if(ch == ' '){
            space++;
        }else if(ch == '\n'){
            enter++;
        }else if(ch>='0'&&ch<='9'){
            digit++;
        }else{
            other++;
        }
    }
    printf("letter=%d,digit=%d,space=%d,enter=%d,other=%d\n",letter,digit,space,enter,other);
    return 0;
}


posted @ 2022-03-17 17:53  Godwin_Zhang  阅读(322)  评论(0编辑  收藏  举报