Reputation: 53
I am trying to count the number of letters of a word before the space. For eg. "Hello how" is my input string and I am trying to count the number of letters in the first word.
#include<stdio.h>
#include<string.h>
int main()
{
char a[30];
int count = 0;
printf("Enter the string.\n"); // Enter hello how as string here.
gets(a);
for ( i = 0; a[i] != '\0'; i++ )
{
while( a[i+1] != ' ' )
count++;
}
printf("%d\n",count);
}
This is a small part of a bigger code, I am actually expecting the value of count to be 5 but it gets into some sort of infinite loop which I am unable to figure out. If I use if instead of while , I get the expected answer. I know gets is not very reliable and I will not use once I get better at programming so it will be kind of you to post your answer about the loop instead of gets. Thank You.
Upvotes: 0
Views: 105
Reputation: 1633
Use '\0'
instead of '/0'
in the for loop condition and also the while loop condition will never be false because i remains the same
Upvotes: 1
Reputation: 162164
The expression within the while statement does not depend on count
. So with every iteration of the while loop the count
gets incremented, but that has no influence on the while conditional, hence it will loop ad infinitum or never, depending on the character at a[i+1]
.
In addition to that, the conditional statement for the for loop is not written correctly either. The string escape for a NUL character is \0
(backslash). Or you can just compare against a 0
literal, which has exactly the same outcome (though when it comes to the subtleties of C it does not mean exactly the same, but that's splitting hairs).
Upvotes: 4
Reputation: 361564
The NUL character is written with a backslash (\
), not forward slash (/
).
for (i = 0; a[i] != '\0'; i++)
Furthermore, the inner loop will not terminate because you're not incrementing i
.
while (a[i] != ' ') {
i++;
count++;
}
Actually, you should not really have two loops. One loop is all you need.
for (i = 0; a[i] != '\0' && a[i] != ' '; i++) {
count++;
}
Upvotes: 4