in this function Id like to limit the try again to 2 tries in the while loop and then send them to the pit of misery and end program. How would I go about that? can I use a break? something < 3? id appreciate your help
int obs1()
{
int choice, tries{ 1 };
std::cout << "What character is at the end of most C++ program statements ?\n"
<< " 1. ( $ )\n"
<< " 2. ( * )\n"
<< " 3. ( ; )\n"
<< " 4. ( : )\n"
<< " Enter 1, 2, 3 or 4 \n";
std::cin >> choice;
while (choice != 3)
{
std::cout << " try again\n";
std::cin >> choice;
if(tries = 3)
return 0;
tries++;
}
std::cout << " Thats correct\n";
return 0;
}
Also, you should always initialize your variables (at least that's what every book on c++ I've ever read has told me)
so instead of
int choice;
do
int choice = 0;
The reason why you should initialize with a value is because, your computer reserves a place in memory for your variable when you declare it (probably either 4 or 8 bytes for an integer), if this memory was previously in use it could contain random garbage which could cause problems much later on for you.
ok now I see. thanks. In visual studio they usually remind you in the way of an error statement when you don't initialize Thanks again to both of you for the help.
appreciate it
It's a newer form of variable initilization and it's set to one because it is tested and incremented each time the while loop executes so the program knows how many guesses have been made and when to break out of the loop.
You can initialize variables in whichever way you prefer.
Either
int choice, tries{ 1 };
or
int choice, tries = 1;
or even
int choice, tries( 1 );
These three statements all accomplish the same exact thing; declare two variables and initialize both of them with the integer literal 1.
I personally use the original form of initialization
int choice, tries = 1;
It's best to choose one form and stick with it for consistency and readability when you come back to code you have written.