looping back to start of do while loop [C++] - c++

I need help for looping back on the start of the program [C++].
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));
int rand_number = rand() % 101;
int number;
int counter = 1;
cout << "NUMBER GUESSING" << endl;
cout << "Try to guess number from 1 to 99: " << endl;
do
{
cout << "Input number: ";
cin >> number;
if (number < rand_number)
{
cout << "Number is too small." << endl;
}
else
{
if (number > rand_number)
{
cout << " Number is too big." << endl;
}
}
number++;
} while (number != rand_number);
cout << "Great! You guessed it in " << number << "th try." << endl;
cout << "Do you want to play again [Y/N]: ";
cin >> Y;
cin >> N;
// dont know how to proceed
return 0;
}
I need help for looping back on the start when it asks me if I want to play again and answer Yes "Y", if I answer No "N" it says Goodbye. Any help would be appreciated, Thanks.

Similar to how you are using a do while, try adding an outer while loop that checks if the N key was pressed

You could create a boolean playAgain which would start as true. If the player says no, set it to false. You can then put your do while in another do while(playAgain). This would loop the game until the player says he does not want to play again.

It is not the most orthodox method but it works :) Use goto.
int main()
{
mylabel:
...
if( <condition> )
{
goto mylabel;
}
...
}
If you want to have a more structured program write your main in anther function, say int func() and loop in main based on the return of the function.
int func()
{
...
if( <condition> )
{
return 1;
}
...
return 0;
}
int main()
{
while(func())
{};
return 0;
}

A very easy way to do this is to use nested while loops. You can use what you already have as the inner loop, then have another outside that that checks if the user has put in a Y or not. It can look something like this:
do {
do {
//Get numbers and check them
//...
} while(number != rand_number);
std::cout << "Some message" << std::endl;
std::cin >> option;
} while(option != 'N');
This goes through your loop, then allows the user to choose to continue. If they choose to go again, it will take them back up to the top of the outer while loop, and keep going until they say to stop.
EDIT:
Here would be the complete code:
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));
char option = 'a';
do
{
int rand_number = rand() % 101;
int number;
int counter = 1;
std::cout << "NUMBER GUESSING" << std::endl;
std::cout << "Try to guess number from 1 to 99: " << std::endl;
do
{
std::cout << "Input number: ";
std::cin >> number;
if (number < rand_number)
{
std::cout << "Number is too small." << std::endl;
}
else if (number > rand_number)
{
std::cout << " Number is too big." << std::endl;
}
counter++;
} while (number != rand_number);
std::cout << "Great! You guessed it in " << counter << "th try." << std::endl;
std::cout << "Do you want to play again [Y/N]: ";
std::cin >> option;
} while(option !='N');
std::cout << "Goodbye!" << std::endl;
return 0;
}

Related

Error when passing vectors as parameter in Xcode

I'm working on a program that I've seen other people do online except I'm trying to use functions to complete it to make it somewhat more challenging for me to help me better understand pointers and vectors. The problem I'm having in xcode is I keep getting this error..
Expected ';' after top level declarator
right here on my code,
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers) //<<< Error
{
cout << fixed << setprecision(2);
...
Where I am trying to use vector numbers in my function. Basically I want the numbers from the function passed back so that I can use them in another function I have not created yet. I've googled this error and it seems like no one can give a straight answer on how to fix this problem. Is anyone familiar with how to correct this? By no means is this code finished I'm just trying to get information regarding vectors as a parameter because from what I'm seeing syntax wise on other sites it looks to be correct. Thanks for your feedback.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
#include <iterator>
using namespace std;
struct menuItemType{
string menuItem;
double menuPrice;
};
void getData(menuItemType (&mlist)[8]);
void showMenu(menuItemType (&menu_List)[8], vector<int> numbers);
int main() {
vector<int> temp;
menuItemType menuList[8];
getData(menuList);
showMenu(menuList,temp);
/*
cout << menuList[0].menuItem << " " << menuList[0].menuPrice << endl;
cout << menuList[1].menuItem << " " << menuList[1].menuPrice << endl;
*/
return 0;
}
void getData(menuItemType (&mlist)[8]){
string Str;
ifstream infile;
infile.open("cafe135.txt");
if(infile.is_open())
{
for (int i = 0; i < 8; ++i){
infile >> mlist[i].menuItem >> mlist[i].menuPrice;
}
}
else cout << "Unable to open file";
}
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers)
{
cout << fixed << setprecision(2);
string choice;
cout << "Would you like to view the menu? [Y] or [N]: ";
cin >> choice;
cout << endl;
int x = 3;
int count = 1;
while (choice != "Y" && choice != "N" && choice != "y" && choice != "n")
{
if (count == 4){
return;
}
cout << "Error! Please try again ["
<< x
<< "] selections remaining: ";
cin >> choice;
cout << endl;
x--;
count++;
}
if (choice == "N" || choice == "n"){
return;
}
else
{
cout << "___________ Breakfast Menu ___________" << endl;
for (int i = 0; i < sizeof(menu_List)/sizeof(menu_List[0]); ++i)
{
cout << "Item "
<< (i+1)
<< ": "
<< menu_List[i].menuItem
<< " "
<< menu_List[i].menuPrice
<< endl;
}
cout << endl;
string itemSelection = " ";
//int str_length = 0;
cout << "Select your item numbers separated"
<< " by spaces (e.g. 1 3 5) Select 0 to cancel order: ";
cin.ignore();
getline(cin, itemSelection);
if (itemSelection == "0")
{
return;
}
vector<int> vectorItemSelection;
stringstream text_stream(itemSelection);
string item;
while (getline(text_stream, item, ' '))
{
vectorItemSelection.push_back(stoi(item));
}
int n = vectorItemSelection.size();
int arr[n];
for (int i = 0; i < n; i++)
{
arr[i] = vectorItemSelection[i];
}
}
}
Compare how menu_List is declared in this line
void showMenu(menuItemType (&menu_List)[8], vector<int> numbers);
and this line
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers)
The first one is correct.
But I have to agree with the comments above, you are mixing up a lot of different things here. Just use vectors, 99% of the time it's the right thing to do anyway. and it's easier to learn one thing at a time.
Prefer to write your code like this
void getData(vector<menuItemType>&);
void showMenu(vector<menuItemType>&, vector<int> numbers);
int main() {
vector<int> temp;
vector<menuItemType> menuList(8);
...
See? Just use vectors everywhere.

Play again option in C++ not working for number guessing game

When the user inputs 'Y' to try again, the game runs but only gives the user 1 try instead of 3 tries. Program works fine the first time it runs with 3 tries. I'm guessing something is wrong with my loop that it does not reset the number of tries? Let me know if there's any other way I could write my code to make it cleaner/better. Thanks a bunch.
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int guessNum;
int randomNum;
int Tries = 0;
int startGame()
{
cout << "Number: ";
cin >> guessNum;
return guessNum, Tries;
}
int main(int a, int b)
{
while (true) {
a = guessNum;
b = Tries;
char ans;
// Random number
srand(time(NULL));
randomNum = rand() % 20 + 1;
// Introduction
cout << "Guess a number between 1 to 20. You have three attempts." << endl;
do
{
startGame();
if (guessNum < randomNum)
{
cout << "Wrong! It is too low." << endl;
}
else if (guessNum > randomNum)
{
cout << "Wrong! It is too high." << endl;
}
Tries++;
}
while (guessNum != randomNum && Tries < 3);
if (guessNum != randomNum) // Wrong answer & run out of tries
{
cout << "Oops.. All attempts used. The answer is " << randomNum << endl;
}
else if (guessNum == randomNum) // User guessed correct number
{
cout << "Yes! You are correct!" << endl;
}
cout << "Try again?";
cin >> ans;
cin.ignore();
if (ans == 'N')
{
cout << "Thanks for playing!";
break;
}
}
}
EDITED V1
#include <iostream>
#include <ctime>
using namespace std;
int guessNum;
int startGame()
{
cout << "Number: ";
cin >> guessNum;
return guessNum;
}
int main()
{
while (true) {
int randomNum;
int Tries = 0;
char ans;
// Random number
srand(time(NULL));
randomNum = rand() % 20 + 1;
// Introduction
cout << endl << "Guess a number between 1 to 20. You have three attempts." << endl;
do
{
startGame();
if (guessNum < randomNum)
{
cout << "Wrong! It is too low." << endl;
}
else if (guessNum > randomNum)
{
cout << "Wrong! It is too high." << endl;
}
Tries++;
}
while (guessNum != randomNum && Tries < 3);
if (guessNum != randomNum) // Wrong answer & run out of tries
{
cout << "Oops.. All attempts used. The answer is " << randomNum << endl;
}
else if (guessNum == randomNum) // User guessed correct number
{
cout << "Yes! You are correct!" << endl;
}
cout << "Try again? Y/N: ";
cin >> ans;
cin.ignore();
ans = toupper(ans);
if (ans == 'N')
{
cout << endl << "Thanks for playing!";
break;
}
else
{
Tries = 0;
}
}
}
Actually, your program has several defects.
Firstly, If you wonder why the game behaves unexpected way after the first one, You did not set back the Tries to 0 after playing the game.
And, int startgame() should return only one variable. You are trying to return guessnum and Tries at the same time. The only reason the first game is running as expected is that you are using global variables, which is also considered as a bad practice(Some company may fire you if you use it without any good reason).
Furthermore, you are getting two int function arguments from main call, which is not valid. (main function signature should be int main(void) or int main(int argc, char* argv[])). I am surprised that the compiler did not catch this error.
And the variables (int a, int b) are actually not used. When you find unused variables, it is usually a good practice to remove them for maintainability.
So int Tries = 0; is a global variable. It's set before main().
You basically have
int Tries = 0;
main()
{
while (true) {
do
{
Tries++;
} while(Tries < 3);
}
}
Do you see that for each iteration in while, the value of Tries from the previous iteration is used? You would need to reset it before iterating again.
But there is no reason to have "Tries" as a global variable since you only need to know about it in the while(true)-loop. This is generally the case for a variable - put it to the closest scope possible:
main()
{
while (true) {
int Tries = 0;
do
{
Tries++;
} while(Tries < 3);
}
}
Now it's correctly reset between loops, and it is clear it is only needed for the loop logic.
Try to do the same for you other variables.
Try:
if (ans == 'N')
{
cout << "Thanks for playing!";
break;
}
else
{
Tries = 0;
}

How do I execute previously executed lines of code in C++

I've started to learn how to code in C++ on my spare time, using different sites and apps that someone who has also learned C++ online provided me with. By now, I know the most basic commands. I've tried an exercise given by a program, and I'm given the information that someone is going on a vacation, and needs to know how much baggage he can bring with him. The limit to how many baggages he can carry is 45, and I have to display a different output if the baggages are below, above or the same as the limit (45 baggages). I have done some coding, and I ended up with this:
#include <iostream>
using namespace std;
int main()
{
const int limit = 45;
int bag;
cout << "Please type your number here: ";
cin >> bag;
string yn;
int keep = 0;
if (limit < bag)
{
cout << "You passed the limit." << endl;
};
if (limit == bag)
{
cout << "Just enough." << endl;
};
if (limit > bag)
{
cout << "You got space." << endl;
};
++keep;
while(keep > 0)
{
int keep = 0;
cout << "Do you want to try another number?" << endl;
cin >> yn;
cout << endl;
if(yn == "yes")
{
int bag = 0;
cout << "Please type your number here: ";
cin >> bag;
if (limit < bag)
{
cout << "You passed the limit." << endl;
};
if (limit == bag)
{
cout << "Just enough." << endl;
};
if (limit > bag)
{
cout << "You got space." << endl;
};
}
else
{
return 0;
}
}
}
I have developed it more than needed -as you can see-, out of my own interest in the problem. I have copied and pasted the 3 IF commands as seen above, and I believe that there is an easier way, with less code, do solve this. What I have thought of is if I could go back and execute some line of code again, either from a line and below (e.g. from line 45 and below), or specific lines of code (e.g. from line 45 to line 60).
I would appreciate it if you thought of another way to solve this problem and posted your code below.
Thank you for your reply.
We all started writing our first C++ program at some time, so allow me to give you some additional feedback:
First of all, avoid writing using namespace std;
Secondly, naming - what is bag, limit, keep and yn? Wouldn't it be much easier to read and understand if they were called bagSize, maximumPermittedBagSize, inputFromUser (you don't really need the variable keep, see below)?
Finally, here is a (roughly) refactored version your program, with duplication removed and comments added.
#include <iostream>
int main()
{
const int maximumPermittedBagSize = 45;
// Loops forever, the user exits by typing anything except 'yes' laster
while(true)
{
std::cout << "Please type your number here: " << std::endl;
//Declare (and initialize!) variables just before you need them
int bagSize = 0;
std::cin >> bagSize;
if (bagSize > maximumPermittedBagSize)
{
std::cout << "You passed the limit." << std::endl;
}
else if (bagSize == maximumPermittedBagSize )
{
std::cout << "Just enough." << std::endl;
}
else
{
std::cout << "You got space." << std::endl;
}
std::cout << "Do you want to try another number?" << std::endl;
std::string inputFromUser = "";
std::cin >> inputFromUser;
std::cout << std::endl;
//Leave the loop if the user does not answer yes
if(inputFromUser != "yes")
{
return 0;
}
}
}
You can simply run a while loop and do like this:
#include <iostream>
using namespace std;
int main()
{
const int limit = 45;
int bag;
string yn = "yes";
while(yn == "yes")
{
cout << "Please type your number here: ";
cin >> bag;
if (limit < bag)
{
cout << "You passed the limit." << endl;
}
else if (limit == bag)
{
cout << "Just enough." << endl;
}
else if (limit > bag)
{
cout << "You got space." << endl;
}
cout << "Do you want to try another number?" << endl;
cin >> yn;
cout << endl;
}
}

Cannot get my getchar() function to work how I want it to work, output is10 not 2 c++

I cannot figure out why my getchar() function is not working the way I want it to work. I am getting 10 not 2. Please take a look.
Main():
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int var, newvar;
cout << "enter a number:" << endl;
cin >> var;
newvar = getchar();
cout << newvar;
return 0;
}
Here is my output:
enter a number:
220
10
Ultimately though I need to be able to distinguish between a '+' '-' or letter or number.
This is maybe not the cleanest way to do it but you can get every char one by one :
#include <iostream>
using namespace std;
int main()
{
int var;
cout << "enter a number:" << endl;
cin >> var;
std::string str = to_string(var);
for(int i=0; i < str.length();++i)
cout << str.c_str()[i] << endl;
return 0;
}
If you enter for example: "250e5" it will get only 250 and skip the last 5.
Edit:
This is just a simple parser and does not do any logic.
If you want to make a calculator I would recommend you to look at what Stroustrup did in his book the c++ programming language.
int main()
{
string str;
cout << "enter a number:" << endl;
cin >> str;
for(int i=0; i < str.length();++i) {
char c = str.c_str()[i];
if(c >= '0' && c <= '9') {
int number = c - '0';
cout << number << endl;
}
else if(c == '+') {
// do what you want with +
cout << "got a +" << endl;
} else if(c == '-')
{
// do what you want with -
cout << "got a -" << endl;
}
}
return 0;
}

How do I loop a variable?

I have made a "program" that just says welcome! Type two numbers you want to be added to each other:
there you type the two numbers and then you get the answer out...
When that is done it says: Press any key to continue . . .
When you press a key the program shuts down, but I want it to restart when you pres any key...
How do I do that? I use Microsoft visual studio express 2013 for windows desktop...
langue is C++
This is my code:
#include <iostream>
#include <limits>
#include <cstdio>
using namespace std;
int Add(int x, int y)
{
cout << "Calculating the sum of " << x << " + " << y << "\n";
return (x + y);
}
int main()
{
cout << " Welcome!\n";
int a, b, c;
cout << "Type two numbers you want to be added to each other: ";
cin >> a;
cin >> b;
c = Add(a, b);
cout << "The answere is: " << c;
cout << "\nShutting down....\n\n";
system("pause");
return 0;
}
To loop, you can use while.
For example:
while (false) {
std::cout << "You will never see this output" << std::endl;
}
bool loop = true;
while (loop) {
std::cout << "Type 'quit' to quit this loop." << std::endl;
std::string input;
// This will grab a *single word* from the input. If you want a line, look
// at std::getline
std::cin >> input;
if (input == "quit") {
loop = false;
}
}
while (true) {
std::cout << "This will be repeated forever" << std::endl;
}
There are also two other forms, do while:
std::string input;
do {
std::cout << "Type 'quit' to quit." << std::endl;
std::cin >> input;
} while (input != "quit");
... and for (which is generally used for loop over a defined list of things):
for (size_t i = 0; i < 10; ++i) {
std::cout << i << " out of 10" << std::endl;
}
Technically you can use any of these loop types for any kind of looping, but I suspect the type you want is either one of the two standard infinite loops (whichever one you prefer):
while (true) {
// stuff to repeat forever
}
for (;;) {
// stuff to repeat forever
}
... or a do while loop similar to the do { ... } while (input != "quit"); loop above.
int main()
{
cout << " Welcome!\n";
int a, b, c;
while (true)
{
cout << "Type two numbers you want to be added to each other: ";
cin >> a;
cin >> b;
c = Add(a, b);
cout << "The answere is: " << c;
cout << "\nPress a key to go again....\n\n";
system("pause");
};
return 0;
}
You can do something like this:
int main()
{
cout << " Welcome!\n";
int a, b, c;
while(true) {
cout << "Type two numbers you want to be added to each other: ";
cin >> a;
cin >> b;
c = Add(a, b);
cout << "The answere is: " << c;
cout << "\nPress any key to continue\n";
system("pause");
}
return 0;
}
Use a do while loop mentioning your condition
before exiting the program so that you can determine when to continue and when to exit
I am not sure I understand your question, but I think this is what you are looking for. Have a boolean that determines if the program will loop or not.
int main() {
// stillRun is true while we want to keep looping the program
boolean stillRun = true;
while(stillRun) {
runProgram() ; // this function has all the other code in your old main() function
cin >> stillRun ;
}
}