I cannot seem to figure out what's wrong with this piece of code. It's not doing what I want it to do:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
steptwo:
cin>> age;
if ( age < 22)
{
cout<< "You are "<<age<<" years old."<<endl;
goto stepthree;
}
elseif (age< 21)
{
cout<< "Please pick an age between 17-21."<<endl;
goto steptwo;
}
elseif ( age> 16)
{
cout<< "Your age is too low. Please pick an age between 17-21."<<endl;
}
I'm trying to have users input age, but it doesn't repeat itself when the user types in an age that's not between 17-21. For example, when I ran this certain piece of code I entered the number 13. It accepted the answer instead of rejecting it and repeating the code. Why is this happening?!
int Switch( 0 );
while( /* Condition */ )
{
std::cin >> age;
if( age < 22 )
Switch = 1;
elseif( age < 21 )
Switch = 2;
elseif( age < 16 )
Switch = 3;
switch( Switch )
{
case 1:
// Code...
break;
case 2:
// Code...
break;
default:
// Code...
break;
}
}
Maybe then will your program work as expected. Note that label: ... goto is still around because it allows for backwards compatibility for legacy C programs. You should never use it
steptwo:
cin>> age;
if ( 17< age >22 )
{
cout<< "You are "<<age<<" years old."<<endl;
goto stepthree;
}
elseif (age< 21)
{
cout<< "Please pick an age between 17-21."<<endl;
goto steptwo;
}
elseif ( age> 21)
{
cout<< "Your age is too high. Please pick an age between 17-21."<<endl;
goto steptwo;
}
elseif (age == 21)
{
cout<< "You are "<<age<<" years old."<<endl;
goto stepthree;
}
Why should I never use the goto statement though? Can you explain to me what legacy C programs are?