Shae Yi
Shae Yi

Reputation: 13

Count number of whitespaces in a character string in c

#include <stdio.h>                  

int main (){
int d=0;                          
int e;                           
while ((e=getchar())!=EOF)  {   
if(e==' '){ 
d++;
}
if(e=='\n')
return 0;
printf("%d",d);

}
}

When i run this code if i type in "hello sir how are you" as my input string, the result i get is 000001111222233334444.. obviously there are 4 whitespace characters, how do i get my code to print out 4 instead of counting the number of whitespaces for every character entered

Upvotes: 1

Views: 6143

Answers (1)

haccks
haccks

Reputation: 106042

You placed printf("%d",d); inside the while loop. Place it outside it to print the aggregate number of spaces.
And finally change return 0 to break, otherwise it will terminate the program without executing the last statement printf("%d",d);.

Upvotes: 2

Related Questions