Loading your workspace…
Loading your workspace…
Read a line of text and count its alphabets, digits, vowels, consonants, spaces and special characters.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char line[200];
int i, letters = 0, digits = 0, vowels = 0, consonants = 0, spaces = 0, special = 0;
char ch;
printf("Enter a line of text:\n");
if (fgets(line, sizeof line, stdin) == NULL) {
printf("Error: no input\n");
return 1;
}
line[strcspn(line, "\n")] = '\0';
for (i = 0; line[i] != '\0'; i++) {
ch = (char)tolower((unsigned char)line[i]);
if (isalpha((unsigned char)ch)) {
letters++;
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
} else if (isdigit((unsigned char)ch)) {
digits++;
} else if (ch == ' ') {
spaces++;
} else {
special++;
}
}
printf("Alphabets : %d\n", letters);
printf("Vowels : %d\n", vowels);
printf("Consonants : %d\n", consonants);
printf("Digits : %d\n", digits);
printf("Spaces : %d\n", spaces);
printf("Special : %d\n", special);
return 0;
}
Input
Hello World 2024!Output
Enter a line of text:
Alphabets : 10
Vowels : 3
Consonants : 7
Digits : 4
Spaces : 2
Special : 1Input
(no input)Output
Enter a line of text:
Alphabets : 0
Vowels : 0
Consonants : 0
Digits : 0
Spaces : 0
Special : 0fgets reads the whole line including spaces, which scanf with %s would stop at. strcspn finds the first newline so it can be replaced with the string terminator.
The character is converted to lower case before the vowel test so that capital letters such as E are counted as vowels too. ctype functions take an unsigned char value to stay safe with non-ASCII bytes.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
Hello World 2024!
Expected output
Enter a line of text: Alphabets : 10 Vowels : 3 Consonants : 7 Digits : 4 Spaces : 2 Special : 1
Expected output
Enter a line of text: Alphabets : 0 Vowels : 0 Consonants : 0 Digits : 0 Spaces : 0 Special : 0
fgets keeps spaces and reads a whole line; %s stops at the first space.
The index of the first newline, which is then replaced with the terminator.
tolower, isalpha and isdigit.
Every alphabet is either a vowel or a consonant, so the two counts add up to the alphabet count.
It is neither a letter, a digit nor a space, so it falls into the remaining category.
Back to all RCU 21BCA1C1P lab programs.