Reputation: 107
I have been trying to make this function take an array of strings and count the number of words but I keep getting 0 as my answer i.e. it hasn't counted anything. I was wondering if anyone could help me out? I believe the logic is right( i could be wrong) but I am mostly really unsure about the way I would be iterating
thank you!!
Here is my code:
int fWords (char **array, int index) {
int number = 0;
int i = 0;
int in = 0;
int j = 0;
int length = 0;
while (i < index) {
length = strlen (array[i]);
for (j = 0; array[i][j] < length; j++) {
if (isspace(array[i][j]) != 0) {
in = 0;
}
else if (in == 0) {
in = 1;
number++;
}
}
i++;
}
return number;
}
Upvotes: 1
Views: 69
Reputation: 682
You need to reset in after every run of the inner loop. Something like this
while (i < index) {
length = strlen (array[i]);
in = 0;
//^^^^^^^
for (j = 0; j < length; j++) {
if (isspace(array[i][j]) != 0) {
in = 0;
}
else if (in == 0) {
in = 1;
number++;
}
}
i++;
}
Upvotes: 1
Reputation: 726589
This condition is incorrect:
for (j = 0; array[i][j] < length ; j++)
// ^^^^^^^^^^^^^^^^^^^^
it should be simply
for (j = 0; j < length ; j++)
// ^^^^^^^^^^
This will fix the problem with zero.
Upvotes: 0