In: Computer Science
In the language c using the isspace() function: Write a program to count the number of words, lines, and characters when user enter statements as input. A word is any sequence of non-white-space characters.
Have the program continue until end-of-file. Make sure that your program works for the case of several white space characters in a row. The character count should also include white space characters.
Example of the user input could be the statement below:
You're traveling through
another dimension;
a dimension not only
of sight and sound,
but of mind.
#include <stdio.h>
#include<stdlib.h>
int main()
{
char data[1000]; // variable to store the input
char ch; // char variable to take a input
int index = 0,charCount = 0, wordCount =0,lineCount = 1, i=0;
printf("Enter the Input ( hit ctrl + D(in linux) ctrl+Z(in windows)
):\n");
while(ch != EOF) // terminates if user hit ctrl + D(in linux)
ctrl+Z(in windows)
{
ch = getchar();
data[index] = ch;
index++;
}
data[index] = '\0';// inserting null character at end
if(index==1){ // if nothing everyting counts to 0(zero)
charCount = 0;
wordCount =0;
lineCount =0;
}
// looping until index-1 times (-1 beacause last char is null, we
need not to be considered)
else {
for(i=0;i<index-1;i++){
charCount++;
if(data[i] == '\n'){
lineCount++;
}
else if(isspace(data[i]) || data[i] == '\n'){ // current char is
space
if((!isspace(data[i-1]) && i !=0)){ // previous char is not
char (to elemenate multiple space condition)
wordCount++;
}
}
}
if(!isspace(data[index-3])){ // if last char is not space then we
need to add wordcount
wordCount++;
}
}
printf("\nline Count : %d \nword Count : %d \nchar Count : %d
\n",lineCount,wordCount,charCount);
return 0;
}
ScreenShot:
