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

analyze:

    In the main function main, the program first defines a character variable c, and four integer variables letters, k, s and o, and initializes their values ​​to 0. Then use the printf function to output a prompt message and let the user enter a line of characters.

    Next, the program reads the characters entered by the user from the standard input through the while loop structure and the getchar function, and performs statistical operations based on their type. Specifically, if it is an English letter, add 1 to the number of letters; if it is a space character, add 1 to the number of spaces k; if it is a number, add 1 to the number s of digits; otherwise, add 1 to the number of other characters o plus 1.

    Finally, the program uses the printf function to output the statistical results, including the number of letters, spaces, numbers, and other characters.

Code:

#include<stdio.h>
int main()
{
	char c;
	int letters=0,k=0,s=0,o=0;
	printf("请输入一行字符:\n");
	while((c=getchar())!='\n')
	{
		if(c>='a'&&c<='z'||c>='A'&&c<='Z')
			letters++;
		else if(c==' ')
			k++;
		else if(c>='0'&& c<='9')
			s++;
		else
			o++;
	}
	printf("字母数:%d\n空格数:%d\n数字数:%d\n其他字符数:%d\n",letters,k,s,o);
	return 0;
}

operation result:

Guess you like

Origin blog.csdn.net/m0_63002183/article/details/134627138