Use "goto" statement to return to the code marked above, and the marked "scanf" statement will not be executed again. How to solve this problem?
I want "scanf" to execute again instead of skipping it, resulting in a constant loop
Put the code you need help with here.
while (x != a)
{
label:int i = scanf_s("%d", &x);
if (i == 1)
{
if (x > a)
{
printf("biger\n");
n++;
}
if (x < a)
{
printf("smaller\n");
n++;
}
}
else
{
x = 0;
goto label;
}
}
while (x != a)
{
int i = scanf_s("%d", &x);
if (i == 1)
{
if (x > a)
{
printf("biger\n");
n++;
}
if (x < a)
{
printf("smaller\n");
n++;
}
}
else
{
int ch;
while( (ch=getchar()) != EOF && ch != '\n') ;
}
}
This will loop just fine until the user manages to guess the value of a.
No messy goto required.
In this code sample gotostatement is bad, there are cases where goto makes code more clear.
The rules as to when use to use gotois this:
if gotostatement would skip initialization of any variables, then it should not be used.
if gotostatement jumps back in execution it should "probably" not be used.
if gotostatement is used to jump forward with the goal to normaly exit current function it's perfectly valid if that makes the code more readable or it takes less boilerplate code to write.
also a general rule is, the gotois more dangerous the more labels there are.
that is more labels is more dangerous than more gotostatements.
Knowing that, who ever told you to use goto in this sample code is giving you a bad sample as to when and how to use goto.
EDIT:
Btw. be aware of people who tell that gotoshould never be used. gotois a valid and useful language feature, saying it should absolutely never be used is wrong.
There are cases where gotois good, but these cases are very rare, you can find plenty of examples online where gotois good and sample where it is bad.
the marked "scanf" statement will not be executed again
Oh it executes, it just keeps failing. After all, if it fails once then it won't read offending characters. That means the next time you call it, it just tries to read the same character and fails again. Line 20 of Salem C's post skips the rest of the input line so that the next call to scanf() will hopefully try to read the next number.