Experiment 3-4 Statistical Characters (15 points)

This question requires writing a program, enter 10 characters, and count the number of English letters, spaces or carriage returns, numeric characters and other characters.

Input format:

Enter 10 characters. The last carriage return indicates the end of the input, which is not counted.

Output format:

letter = 英文字母个数, blank = 空格或回车个数, digit = 数字字符个数, other = 其他字符个数Output according to the format in one line .

Input sample:

aZ &
09 Az

Sample output:

letter = 4, blank = 3, digit = 2, other = 1

Code:

# include <stdio.h>
# include <stdlib.h>

int main() {
    
    
    int i = 1,letter = 0,blank = 0,digit = 0,other = 0;
    char x;
    while (i <= 10) {
    
    
        scanf("%c",&x);
        if ((x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z')) {
    
    
            letter += 1;
        }else if (x == ' ' || x == '\n') {
    
    
            blank += 1;
        }else if (x >= '0' && x <= '9') {
    
    
            digit += 1;
        }else {
    
    
            other += 1;
        }
        i += 1;
    }
    printf("letter = %d, blank = %d, digit = %d, other = %d",letter,blank,digit,other);
    return 0;
}

Submit screenshot:

Insert picture description here

Problem-solving ideas:

Here ASCIIare several special sections of code, such as 0~9the ASCII code corresponding to the number 48~57, but we don’t have to remember, the chartype can be directly compared when comparing! In addition, some friends may be worried that my program usually ends with a carriage return, so if you enter a carriage return in the middle, will it jump out of the program? In fact, you can try to copy it to the input completely, and the result will be correct output!

Guess you like

Origin blog.csdn.net/weixin_43862765/article/details/114436570