The Program in C that will read a line of text and display number of words and number of characters is given below:
#include <stdio.h>
#include <string.h>
int main() {
char input[1000];
printf("Enter a line of text: ");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = 0; // remove newline char
int words = 1, characters = 0;
int i = 0;
while (input[i] != '\0') {
characters++;
if (input[i] == ' ') {
words++;
}
i++;
}
printf("Number of words: %d\n", words);
printf("Number of characters: %d\n", characters);
return 0;
}
Output:
Enter a line of text: codeauri is dope bros sis ,isnt it?
Number of words: 7
Number of characters: 35
Pro-Tips💡
This program uses the fgets()
function to read a line of text from the keyboard, and stores it in the input
variable.
It then removes the newline character that is appended to the input by fgets
by replacing it with a null terminator.
It initializes two variables, words
and characters
to 1 and 0 respectively, and uses a while loop to iterate through each character in the input string.
If the current character is a space, it increases the value of the words
variable, and for each character it increases the value of the characters
variable.
Finally it prints the number of words and characters respectively, which is stored in words
and characters
variables.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.