Hello! I fell into an infinite loop while practicing c, but I can't solve it.
Here's the situation.
If you receive an integer between 1 and 10, you have to exit the for statement and re-enter it when you receive other numbers.
Below is the code you created.
int testcase;
for (;;) {
testcase = 0;
printf("enter the number of testcase : ");
scanf_s("%d", &testcase);
if (testcase > 10 || testcase < 1) {
printf("wrong number. please enter a number between 1 and 10 in integer type. \n");
}
else {
break;
}
}
The problem here is that if you enter a number or character with a decimal place outside the range,
printf("wrong number. please enter a number between 1 and 10 in integer type. \n");
The sentence keeps running.
I don't know why an infinite loop occurs even if I observe what value the variable testcase has according to the input in debugging mode.
Please give us a lot of suggestions! Thank you (__)
c scanf for
This is caused by the fact that the incorrect values received through scanf continue to remain in the input stream and mess with! To solve the problem, empty the input stream properly.
It's a very annoying bug when you first encounter it.
Anyway, please refer to the code below.
The added line is a line of while (getchar()!='\n') {}
to empty the input stream.
Of course, this code is just an example, and there are many other good ways :3
#include <stdio.h>
int main(void) {
int testcase;
while (1) {
testcase = 0;
printf("enter the number of testcase : ");
scanf_s("%d", &testcase);
if (testcase > 10 || testcase < 1) {
while (getchar()!= '\n') {} // empty input stream
printf("wrong number. please enter a number between 1 and 10 in integer type. \n");
}
else {
break;
}
}
}
886 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
609 Uncaught (inpromise) Error on Electron: An object could not be cloned
568 Who developed the "avformat-59.dll" that comes with FFmpeg?
599 GDB gets version error when attempting to debug with the Presense SDK (IDE)
© 2024 OneMinuteCode. All rights reserved.