How to loop after a loop statement is completed? - c++

int guess_number = (gen() % 1000);
cout << guess_number;
int number = 0;
cout << "Number:";
cin >> number;
do
{
if (number>guess_number)
{
cout << "Too High"<<"\n";
cin >> number;
}
else if (number<guess_number)
{
cout << "Too Low"<< "\n";
cin >> number;
}
} while (number != guess_number);
int again=0;
cout << "Wanna Play Again!";
cin >> again;
I'm making a guessing game, but must loop the game if the player answers 1 after "Wanna Play Again!" I'am working with if,for,do, switch, and while statements. Its an assignment I was given and I just can't seem to figure out exactly how to loop the entier statement. I have made several attempts, but it either exits the program or continually prints "Wanna Play Again!".

How about wrapping the existing do/while with a another for the play again condition ?
int again =0;
do{
do{
//existing code
} //end inner while
cout << "Wanna Play Again?";
cin >> again;
} while(again != 0); //or whatever makes sense for the condition

Related

How to go back to a certain point in the code

I'm new to C++ programming.
I just want to know if there is any way to go back to a certain point in the code without using a while or a do-while loop.
Here is an example:
int a;
cout << "What's 2+2?";
cin >> a;
if (a==4) {cout << "Nice!";}
else {cout << "WRONG! Try again!";}
So, if the player fails, I want to ask the question again, so going back to:
cout << "What's 2+2?";
Is there any way to do it without using a loop?
You want to repeat something until a condition is satisfied. That is the definition of a loop, and there are many ways to write loops in C++. The example you showed is best handled using a do-while loop:
int a;
do
{
cout << "What's 2+2?";
cin >> a;
if (a == 4) {
cout << "Nice!";
break;
}
cout << "WRONG! Try again!";
}
while (true);
Though you could use a while or for loop instead:
int a;
while (true)
{
cout << "What's 2+2?";
cin >> a;
if (a == 4) {
cout << "Nice!";
break;
}
cout << "WRONG! Try again!";
}
int a;
for(;;)
{
cout << "What's 2+2?";
cin >> a;
if (a == 4) {
cout << "Nice!";
break;
}
cout << "WRONG! Try again!";
}
That being said, to answer your actual question, you can use a goto statement without any other looping instructions:
int a;
askTheUser:
cout << "What's 2+2?";
cin >> a;
if (a != 4) {
cout << "WRONG! Try again!";
goto askTheUser;
}
cout << "Nice!";
But, goto is rarely used in modern coding, it is not likely to perform any better than a do-while loop after compiler optimizations are applied, and it has limitations on how it can be used.
The preferred language construct for executing a block of code more than once is a loop, which can be of a for, a do-while, or a while form.
So I'd write the code as follows:
int a;
bool correctGuess = false;
while (!correctGuess) {
cout << "What's 2+2?";
cin >> a;
if (a==4) {cout << "Nice!"; correctGuess = true; }
else { cout << "WRONG! Try again!"; }
}
Another way would be the use of recursion, i.e. a function that calls itself until a particular condition is met. Yet this seems to be a to complicated approach for your scenario.
If - for any reason - you are asked to not use such kind of loops, you could use a goto-statement (though this is clearly not the preferred way to do; goto-statements are very rarely used nowadays):
int a;
loop:
cout << "What's 2+2?";
cin >> a;
if (a==4) {cout << "Nice!";}
else {
cout << "WRONG! Try again!";
goto loop;
}
DontDoThis:
...
goto DontDoThis;
That's it.
DontDoThis: is a "label", and goto DontDoThis jumps execution to the specified label. But, like the label's name says, DONT DO THIS! Using goto is concerned bad practice in modern coding, there are better ways to handle looping.
You should initialize a to 0 and then use a while (a != 4) loop. But that's not your question :)
The other loop statement is for
Another way is to use functions - they can be called repeatedly.
Well, if you don't want to use a while or do-while...
for (;;) //same as while(true)
{
int a;
cout << "What's 2+2?";
cin >> a;
if (a==4)
{
cout << "Nice!";
break;
}
else
{
cout << "WRONG! Try again!";
}
}

Programming Principles and Practice: chapter 4 drill part 1

I just can't seem to get this program to work properly. I can get it to accept two integers and print them to the screen. But I can't get the program to terminate when the '|' is used. Once that its entered it loops infinitely. Here is the code that I have so far:
#include "../../std_lib_facilities.h"
int main()
{
int num1 = 0;
int num2 = 0;
char counter = '\0';
cout << "Please enter two integers and press enter. \n";
bool test = true;
while (counter != '|')
{
cin >> num1 >> num2;
cout << "Your numbers are: " << num1 << " " << num2 << endl;
if (cin.fail())
{
cout << "Goodbye!\n";
test = false;
}
else (counter != '|');
cout << "Enter more numbers or press '|' to exit.\n";
}
system("pause");
}
You are using the wrong condition in your while loop. You are never changing counter so the loop will never end. However you do change test to false in the while loop if the input fails. You can change the condition of the while loop to use test instead like
while(test)
{
//...
}
Since counter is no longer being used you can get rid of it completely.
Please note that unless you change to taking in string and parsing the input any input that will cause cin to fail will end the loop not just a |.

loop repeats without prompting the user again?

I have this snippets of code from my original long program, and as much as it looks simple, it doesn't work correctly! I am brand-new to c++ language, but I know in Java that would be the way to do it (Regardless of the syntax).
Simply put, this should ask the user for an input to answer the following multiplication (5*5), however, it should also check if the user entered a wrong input (not number), keep asking the user again and again... Somehow, it keeps running forever without taking a new input!!
I hope to get, not only an answer, but also a reason for such an error!
int main() {
int userAnswer;
bool isValidAnswer = true;
cout << 5 << " * " << 5 << " = ";
cin >> userAnswer;
cin.ignore();
do {
if (cin.fail()) { //user input is not an integer
cout << "Your answer is not valid! Please enter only a natural number: ";
cin >> userAnswer;
cin.ignore();
} else {
isValidAnswer = false;
}
} while (isValidAnswer);
return 0;
}
Well you need to clear the error state before accepting new input. Call cin.clear() then cin.ignore() before trying to read input again.
I would do something like.
cout << "Enter a number: ";
cin >> number;
while(cin.fail())
{
cin.clear();
cin.ignore(1000, '\n'); //some large number of character will stop at new line
cout << "Bad Number Try Again: ";
cin >> number;
}
First, cin.fail() is not going to adequately check if your answer is a natural number or not with the type set to int (could also be negative).
Second, your boolean isValidAnswer is really checking if it's is an invalid answer.
Third (and most importantly), as another answer suggests, you should put in cin.clear() to clear the failure state, and then followed by cin.ignore(), which will remove the failed string from cin.
Fourth, cin will only check if an int exists somewhere in the string. You'll need to perform your own string comparison to determine if the entire input is a int (see answer below, based on this answer).
Updated:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
bool isNum(string line)
{
char* p;
strtol(line.c_str(), &p, 10);
return *p == 0;
}
int main() {
int userAnswer;
string input;
bool isInvalidAnswer = true;
cout << 5 << " * " << 5 << " = ";
while (isInvalidAnswer) {
if (!(cin >> input) || !isNum(input)) {
cout << "Answer is not a number! Please try again:\n";
cin.clear();
cin.ignore();
}
else {
userAnswer = atoi(input.c_str());
if (userAnswer < 0) { //user input is not an integer
cout << "Answer is not a natural number! Please try again:\n";
} else {
isInvalidAnswer = false;
}
}
}
cout << "Question answered!\n";
return 0;
}

C++ - Loop function or program forever? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Made my first C++ program ever. A basic calculator.
Got stuck at this part where I was suppose to make the program repeat.
So at "Point A" you select if you want to count division/addition etc. and it takes you there. When you run it once, it asks if you want to repeat the function (e.g division) or go back to the "Point A" (you just type y[yes] (repeats the division) or n[no](goes to "point A")).
I'm new to C++, haven't got really familiar with loops yet.
Also the code structures make my head spin, so Google didn't help me much.
I've heard about the "goto" function (or whatever you call it) but I was told that i shouldn't be used in this case.
Take a look. The texts, and most of the comments are in Finnish, but I hope you'll get the point from English comments.
#include <iostream>
using namespace std;
float addition(float num1, float num2)
{
return num1 + num2;
}
float substraction(float num1, float num2)
{
return num1 - num2;
}
float multiplication(float num1, float num2)
{
return num1 * num2;
}
float division(float num1, float num2)
{
return num1 / num2;
}
//This function should throw you back to point 'A'
int valinta2{
while (valinta2 == y){
}
}
int main(void)
{
//Point A
float number1;
float number2;
int valinta;
cout << "\n-*-*-*-*-*-*-*-*-*-*\nClaudion Laskin\n-*-*-*-*-*-*-*-*-*-*";
//Select what you want to count
cout << "\n\n\nValitse mita haluat laskea. \n\nVaihtoehdot: " << endl;
cout << "1. Plus-laskut\n 2. Vahennys-laskut\n 3. Kerto-laskut\n 4. Jako-laskut \n\nValinta: ";
cin >> valinta;
if (valinta == 1){
//Addition
cout << "\n\n\n===============\n||Plus laskut||\n=============== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n+\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << addition(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cin.get();
}
else {
if (valinta == 2){
//Subtraction
cout << "\n\n\n===================\n||Vahennys laskut||\n=================== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n-\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << substraction(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cout << "Valinta: ";
cin >> valinta2;
}
else {
if (valinta == 3){
//Multiplication
cout << "\n\n\n================\n||Kerto laskut||\n================ \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n*\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << multiplication(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cin.get();
}
else {
if (valinta == 4){
//Division
cout << "\n\n\n===============\n||Jako laskut||\n=============== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n/\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << division(number1, number2) << "\n----------\n" << endl;
}
}
}
}
system("pause");
return 0;
}
You need to restructure your code to include the while loop in the main method. There would be ways to "go to" your "Point A", but they are messy and shouldn't be used (goto is the keyword here).
So at "Point A", insert
do {
float number1;
// ...
and then down at where you would like to call valinta2 (notice that you don't even call the function at the moment - I'm guessing it would have to be just before the call to system("pause")), do the check of the condition, like so:
} while (...);
And best revisit the chapter on flow control/loops in the C++ tutorial of your choice, e.g. one of those mentioned here: The Definitive C++ Book Guide and List
Alternative to nyarlathotep's perfectly good answer, one method I like using follows this form:
while(true) {
//do stuff
//then when ready to check for exit condition
if(exitCondition == true) { //the ==true part is redundant
break;
}
//do more stuff
//if you need to go to the beginning of the loop and
//skip any code following a point, do this:
if(skipRestOfLoopCondition) {
continue;
}
//you can always check other exit conditions or check
//the same one at multiple places
if(someOtherExitCondition) {
break;
}
//do even more stuff
}
system("pause");
return 0;
As a caveat, you must provide a way for at least one of the if's that result in break; to actually execute, because while(true) loop condition never gets you out of the loop, you can only get out of the loop with a break;.
I am pretty new to this and I don't know if I am right. I can hardly understand your code. However, when I am programming in c for the arduino and I want my code to loop forever I just put
void loop() {// my code follows from here

C++ GetLine() Problem, Command Line Program

I am writing this program for my programming class and it has a bunch of stupid constraints like I must use nested if else statements and I have to use the cin.getLine() to get a players name. It is supposed to grab the name of each player and calculate their batting average.
This is not the entire program but up to the part where I am having an error. When I run this in a command prompt I can recieve the first name fine, but after that the second cin.getline() does not read any input. Suggestions?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
char name1[100], name2[100], name3[100];
int numBat, numHit;
double avg1, avg2, avg3;
// Get Average for Player 1
cout << "What's Your Name? ";
cin.getline(name1, 100);
cout << "How many times have you been at bat? ";
cin >> numBat;
if(numBat < 0 || numBat > 25)
{
cout << "ERROR ::: Number of Times at Bat Cannot Be Less Than 0 or Greater Than 25. Run Program Again." << endl;
return 0;
}
else
{
cout << "How many times have you hit the ball? ";
cin >> numHit;
if(numHit < 0)
{
cout << "ERROR ::: Number Hit Cannot Be Less Than 0. Run Program Again." << endl;
return 0;
}
else
{
// Calculate Average for Player 1
avg1 = numHit / numBat;
// Get Average for Player 2
cout << "What's Your Name? ";
cin.getline(name2, 100);
cout << "How many times have you been at bat? ";
cin >> numBat;
cout << "How many times have you hit the ball? ";
cin >> numHit;
}
}
}
I think it's a buffer problem. Try to flush the cin before the second getline:
cin.clear(); // clear the buffer
cin.sync();
if that does not work, try something like this:
cin.ignore(256, '\n'); // ignore the endline and char(256)
After the getline, you need to output a newline using cout << endl;.
When you use
cin >> numBat;
It doesn't read the newline, so the next cin.getline() will read that and continue.
Use
cin >> numBat;
cin.ignore(80,'\n');