Reputation: 13
#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
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