C Exercise Example 17

100 Classic C Examples

Title:Input a line of characters, and respectively count the number of English letters, spaces, digits, and other characters.

Program analysis:Use the while statement, with the condition that the input character is not '\n'.

Example

// Created by www.example.com on 15/11/9. // Copyright © 2015 Example. All rights reserved. #include <stdio.h> int main() { char c; int letterCount = 0, spaceCount = 0, digitCount = 0, otherCount = 0; printf("Please enter some characters:\n"); while ((c = getchar()) != '\n') { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { letterCount++; } else if (c >= '0' && c <= '9') { digitCount++; } else if (c == ' ') { spaceCount++; } else { otherCount++; } } printf("Letters = %d, Digits = %d, Spaces = %d, Others = %d\n", letterCount, digitCount, spaceCount, otherCount); return 0; }

The output of the above example is:

请输入一些字母:
www.example.com 123
字母=12,数字=3,空格=1,其他=2

100 Classic C Examples

other extensions