Hi guys. I'm new at programming and trying to learn c++. I'm searching alternatives for "goto" function since I know that goto has a bad name among programmers. Here is a part of my codes:
menu:
cout<<"\n1 - Most successful student info\n";
cout<<"2 - Most unsuccessful student info\n";
cout<<"3 - Class average\n";
cout<<"4 - Number of students scored A\n";
cout<<"5 - Number of students scored B\n";
cout<<"6 - Number of students scored C\n";
cout<<"7 - Number of students scored D\n";
cout<<"8 - Number of students scored F\n";
cout<<"9 - Number of students passed Dthe class(A+B+C)\n";
cout<<"10 - Number of students failed the class(D+F)\n";
cout<<"\nSelect an option or type 0 to exit.\n\n";
cin>>opt2;
if(opt2<1 && opt2!=0 || opt2>10)
{cout<<"\nInvalid request. Select an option between 1 and 10.\n";
system("pause");
system("CLS");
goto menu;}
if(opt2==1)
{cout<<"\n*****************************************************************\n\n";
cout<<"Student number: "<<maxNumber<<" Name: "<<maxName<<" Last Name: "<<maxLname<<" Average: "<<maxAv<<" Letter grade: "<<maxLettergrade<<"\n\n";
system("pause");
system("CLS");
goto menu;}
else if (opt2==2)
{cout<<"\n*****************************************************************\n\n";
cout<<"Number: "<<minNumber<<" Name: "<<minName<<" Last name: "<<minLname<<" Average: "<<minAv<<" Letter grade: "<<minLettergrade<<"\n\n";
system("pause");
system("CLS");
goto menu;}
else if (opt2==3)
{cout<<"\n*****************************************************************\n\n";
cout<<"\nClass average= "<<sum/countn<<"\n\n";
system("pause");
system("CLS");
goto menu;}
And it goes like this for every option. So, is there any other way to go back to menu after every option? Thanks in advance.
1. Use functions;
2. Use loops - for, while;
3. Use a switch statement.
Look in the reference & articles section - top left of this page.
The first part should go into a ShowMenu function, the rest should be in a switch with a default clause instead of the test:
if(opt2<1 && opt2!=0 || opt2>10)
A handy looping thing goes as follows:
1 2 3 4 5 6 7 8 9 10
bool Quit - false;
while (!Quit) {
//your code here
//ask user if they want to quit
//convert answer to upper case using toupper function
Quit = true;
}
Another thing - your cout statements don't have to be on one line - you can split them with the same effect:
I saw your answer just now. As I said, I'm really new at c++, like 2-3 weeks experience :D So I code very primitive as you see.. Thanks for all the advices, they are golden for me, I'll certainly follow them :)
Thanks for all the advices, they are golden for me, I'll certainly follow them :)
Thanks & No worries - any time !!
Just 1 more thing - I prefer not to use do loops (My personal preference). I find that they can almost always be written with a while or for loop, however there are some situations where they are a valid use.