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? :?:

while( str != ' ' && str != '\0' )

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? :?:

my dear friend in the first version when you are checking it as while(str!= ' ' || str!= '\0')then the loop will continue untill any of the two condition are satisfied and for a given character either it will be a null or a space so one of the negation statement will always be satisfied and loop will continue to run for infinite no. of times. But if you try the statement like while(str!= ' ' && str!= '\0') then it will run only when both the negations are satisfied so if any of the two character either null or space is encountered it will break.your code will work fine.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.