问题
I am making a program that asks a user to put a input. If the user puts in the input it will show is input and then finish the program. How do I make the program start from the beginning? my code is built like this: (just showing the build not the code itself)
please enter user input:
while (x != y)
{
if ( x == y )
{
printf("printing something");
}
else if (x > y )
{
printf("printing something");
}
else
{
printf("printing something");
}
}
回答1:
int main(void)
{
int num = 0;
while( 1 )
{
printf("This is a game to find the password. Start this game by trying to guess it with numbers from 1 - 100. The program will tell you if you are close or not.\n");
num = 0; // reset the num back to zero
while (num != 65)
{
printf("please enter a number:\n");
num = GetInt();
if (num == 65)
{
printf("Nice!!\n");
break; // exit the while (num != 65)
}
else if (num > 50 && num < 60 )
{
printf("almost there! go higher!\n");
}
}
}
}
回答2:
If you dont mind using goto
:
HERE: please enter user input:
while (x!= y)
{
if ( x == y )
{
printf("printing something");
}
else if (x > y )
{
printf("printing something");
}
else
{
printf("printing something");
}
goto HERE;
}
In this example however as you can see you you never break while. You have to usegoto
carefully.
Edit:
The above code has a mistake. In order to get inside the while
loop x!=y
. But then
you check x==y
which is always false
. So:
HERE: please enter user input:
while (true)
{
if ( x == y )
{
printf("printing something");
break;
}
else if (x > y )
{
printf("printing something");
}
else
{
printf("printing something");
}
goto HERE;
}
Edit 2:
You have only ONE while loop
int num;
//your code here
HERE:
num = GetInt();
while(true)
{
if (num == 65)
{
printf("Nice!!\n");
break;
}
else if (num > 50 && num < 60 )
}
else if (something )
something
}
.
.
.
else{
something
}
goto HERE;
}
valter
来源:https://stackoverflow.com/questions/21291323/how-to-jump-to-the-beginning-of-the-code