Hi, this program is supposed to print the first word of a string ( the whole string could be a single word as well. But it gets stuck in an infinite loop :!: :
#include <stdio.h>
#include <conio.h>
int main()
{
char *str = "This is a sample string";
char word[20];
int i = 0, j = 0;
// This loop is supposed to iterate till
// a space or null character is encountered,
// but it seems to be an infinite loop
while( str[i] != ' ' || str[i] != '\0' )
{
word[j] = str[i];
j++;
i++;
}
word[j] = '\0';
printf("%s", word );
getch();
return 0;
}
But when I write it like this it works:
#include <stdio.h>
#include <conio.h>
int main()
{
char *str = "This is a sample string";
char word[20];
int i = 0, j = 0;
// This works!
while( str[i] != ' ' )
{
if( str[i] != '\0' )
{
word[j] = str[i];
j++;
i++;
}
else
break;
}
word[j] = '\0';
printf("%s", word );
getch();
return 0;
}
What is wrong with the first version? :?: