I made a while loop inside a program and the program reaches the while loop, but it doesn’t execute. I feel like there’s a really tiny error that I’m missing since I’ve been looking at the code for so long.
int strbuf = 100;
char string[strbuf];
char *exit = "exit";
while(!strcmp(string, exit)){
printf("Enter a word to search. Enter exit to quit");
scanf("%s", string);
state = present(fIndex, string);
if(state){
printf("The word %s was found on line %d", string, state);
}
}
EDIT: the input is from the keyboard.
EDIT EDIT: NEW CODE (same problem)
int strbuf = 100;
char string[strbuf];
char *exit = "exit";
printf("Enter a word to search. Enter exit to quit\n");
scanf("%s", string);
while(!strcmp(string, exit)){
state = present(fIndex, string);
if(state){
printf("The word %s was found on line %d", string, state);
}
else printf("The word %s was not found", string);
}
Read the man page for
strcmp:If you have a match,
strcmpwill return 0, and if the two strings don’t match it’ll return a non-zero value.Therefore
while(!strcmp(string, exit))is really saying, while the strings match, continue to loop.stringis also uninitialized and contains junk, causing undefined behaviour. Either initialise it first or or use ado..whileloop if your loop must execute at least once.