C language practice question 17

foreword

Woooooooooooooo~ The beauty is either catching up with homework or on the way to do it. P I dare not post such beautiful travel photos, because I am afraid that Master will see me and ask me to hand in my homework. (╥╯^╰╥)
I hope Master will not read this article, my draft box is full of corpses, and I am currently picking them up one by one. Too miserable for me ((٩(//̀Д/́/)۶))

Question seventeen

Topic:
Enter a line of characters, and count the number of English letters, spaces, numbers and other characters in it.

Sui Sui Nian:
Wow ha ha ha, another question I know.

My thoughts:
1. This question is different from the previous ones. It is defined in the form of character char at the beginning, and subsequent operations will also be performed according to character operations.
2. Input: character
Output: number
3. Analysis: first define the input as a character type, and then define the output as an integer. Because it is to calculate the number of English letters, spaces, numbers and other characters, all can be calculated one by one with if-else structure.

My process:

#include<stdio.h>
int main()
{
    
    
    char c;//定义输入格式
    int letters=0,spaces=0,digits=0,others=0;//给变量赋初值这步也可以在定义的时候完成
    printf("请输入任意字母,数字或者符号:\n");
    while((c=getchar())!='\n') /*gatchar函数为C语言提供的标准输入函数之一,
							   通过该函数实现从终端键盘读字符的功能。*/
    {
    
    
        if((c>='a'&&c<='z')||(c>='A'&&c<='Z'))//一开始我只考虑到小写字母的情况,突然醒悟过来还有大写字母。
            letters++;
        else if(c>='0'&&c<='9')
            digits++;
        else if(c==' ')//这个中间是有一个空格的,不是啥也没有╮( ̄▽ ̄")╭
            spaces++;
        else
            others++;
    }
    printf("字母=%d,数字=%d,空格=%d,其他=%d\n",letters,digits,spaces,others);
    return 0;
}

Running results:
insert image description here
Summary
It is easiest to use if-else for this question. I have written more detailed step analysis in the comments of the code. The main reason is to use the character input function, which I haven't practiced before. Now it is clearer to know its usefulness. This C language 100 questions is really good.

Guess you like

Origin blog.csdn.net/weixin_52248428/article/details/116459082