Ed Hernandez
Ed Hernandez

Reputation: 31

Counting the number of spaces in C program

Lowercase and uppercase letters, special characters and numbers are working just fine. The program can't count total characters and spaces properly. What should I add to make this work? Appreciate your help!

#include<stdio.h>
#include<string.h>
#include <ctype.h>
#include<conio.h>

main(){
char cMessage[100];
int  cChar,cLow=0, cUp=0, cSpec=0, cSpace=0, cNum=0;

printf("Enter your message: ");
scanf("%s", cMessage);

int x=0;
while(x<strlen(cMessage)){

printf("%c",cMessage[x]);
cChar++;

if(islower(cMessage[x])){ cLow++;}

else if(isupper(cMessage[x])){ cUp++;}

else if(cMessage[x] == ' '){ cSpace++; }

else if(isdigit(cMessage[x])){ cNum++; }

else{ cSpec++;
}
x++;
}
printf("\nTotal Characters: %d", cChar);
printf("\nTotal Lowercase Letters: %d", cLow);
printf("\nTotal Uppercase Letters: %d", cUp);
printf("\nTotal Special Characters: %d", cSpec);
printf("\nTotal Spaces: %d", cSpace);
printf("\nTotal Numbers: %d", cNum);
getch();



}

Upvotes: 0

Views: 93

Answers (1)

Achal
Achal

Reputation: 11921

The program can't count total characters and spaces properly ? One reason is that the statement scanf("%s", cMessage); won't read the white spaces or read upto space only. If you want to read the cMessage with whitespace then use fgets().

fgets(cMessage,sizeof(cMessage),stdin);/* use fgets() instead of scanf() */

Or you can use scanf() like this

scanf("%[^\n]", cMessage);/* it read the whitespaces also */

Read the manual page of fgets() here https://linux.die.net/man/3/fgets

Upvotes: 3

Related Questions