I want to make a program in C that count how many white spaces are between words. This is the code, but I can't solve the error that occurred.
#include<stdio.h>
#include<string.h>
int main(){
char str[200];
int a[200];
int i, z, c;
int WordsCount = 0;
puts("Give String");
fflush(stdin);
gets(str);
for (int i=0; str[i]!= '\0'; i++){
if (str[i] == ' '){
WordsCount++;
int count = 0;
for (z=i; str[z]!=' '; z++ ){
count++;
}
i = z;
a[WordsCount-1] = count;
}
}
for (int c=0; c<WordsCount; c++){
printf("%d", a[c]);
}
}
At least one problem:
str[z]!=' '
is always false
When str[i] == ' '
is true, z=i; str[z]!=' '
z=i; str[z]!=' '
is false.
Check the next character.
if (str[i] == ' '){
WordsCount++;
//int count = 0;
int count = 1;
//for (z=i; str[z]!=' '; z++ ){
for (z=i; str[z+1]!=' ' && str[z+1]!='\0'; z++ ){
count++;
}
i = z;
a[WordsCount-1] = count;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.