This is my second day learning C++. How would i go about restarting this program? I would like to enter a grade number, receive the grade letter then have the program start over and ask for my grade number again...
im using C::B if that matters..
Pretty simple fix for this would be to use a loop. In this particular case, a while loop will be the loop of choice.
A while loop will continue until the loop condition is false. So what I will do is have a continue bool variable and set to true. After a grade is displayed to the console it will then ask the user to continue. If the user wants to continue then it will not change the bool variable but if the user wants to exit the program it will then change the variable and then exit the while loop which then will exit the program.
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
int x;
bool continueYN = true;
while (continueYN)
{
cout << "Enter grade: ";
cin >> x;
if ( x >= 90 )
{
cout << "Your grade is A! \n";
}
elseif ( x >= 80 )
{
cout << "Your grade is B! \n";
}
elseif ( x >= 70 )
{
cout << "Your grade is C! \n";
}
elseif ( x >= 60 )
{
cout << "Your grade is D! \n";
}
else
{
cout << "Your grade is F! \n";
}
int YN;
cout << "would you like to continue? Enter 1 for yes, 2 for no" << endl;
cin >> YN;
if (YN == 2) //only checking to see if user entered 2 since this exits loop
continueYN = false;
}
}
of course there are better ways to do this like using a do while loop and so on but I decided to keep it simple for you since you are new. Also, I cannot remember exactly if C++ uses bool or boolean for boolean variables so maybe try both until one works!
One addition to erock's suggestion would be to use break to end the loop instead of a Bool that remains in memory for the rest of that scope.
You mean after the loop ends?, how is that different? You still need to use a variable to trigger the break,
It could be done with any of the ways Dput mentioned, but a do/while loop (or game loop) is the better method for something like this since it will run at least once no matter what the flag is set at. IMO, using break for something like this is little different than using GOTO.
ive been working with networks for 8 years and went back to school last year for IT. so far ive had to take a visual basic and javascript class and soon a java class. needless to say i feel i got bit by the programming bug.
on thing i noticed on the solution that erock 88 suggested is, howcome there is no open curly bracket on the second if statement?
An if statement will auto encapsulate the next line of code if no brackets were defined, else use curly brackets to encapsulate procedures of an amount greater than one..
Example:
if(true)
---Do this - only if true;
//versus
if(true)
{
---Do all of this till the next '}'
---And this stuff too, before the next '}'
}