I took out some part of the code in the while loop, but I want to break out of the fgets() while loop until it reads in a character 'q'. But the program still wants some input and it doesn't end the program. Why doesn't this method work?
char buffer[300];
while (fgets(buffer, 300, stdin))
{
int i;
for (i = 0; i < 300; i++){
if (buffer[i] == 'q')
break;
}
}
An alternative to the good recommendation given by @John3136 would be to create a flag which you can use to conditionally break out of the outer loop if you hit the letter 'q'
in the inner loop. The following code lets you keep the same general structure you had originally:
while (fgets(buffer, 300, stdin)) {
bool is_break = false;
int i;
for (i = 0; i < 300; i++){
if (buffer[i] == 'q') {
is_break = true;
break;
}
}
if (is_break)
break;
}