Writing a program which continuously asks the user for input - c++

I am trying to make a program where the user tries to guess a randomly generated number; basically, a classic number-guessing game.
My program is running pretty well but I can't find out how to ask the user to play the game again if the guessed number is correct, and also how to keep asking the user for guesses if the guessed number is incorrect.
Can somebody help me accomplish this?

You can use a while loop to keep asking the user for input, as so:
int guess, answer = rand()%10;
while(cin >> guess){ // keeps on asking the user for input
if(guess > answer){cout << "Too high!" << endl;}
else if(guess < answer){cout << "Too low!" << endl;}
else{
cout << "Good job!" << endl;
break;
}
}

Related

(Total Beginner) Unsure why goto does not work in program [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 months ago.
Improve this question
Hey so I only started C++ 2 days ago, so please try to keep the answer simple, otherwise probably won't understand it, thanks!
I tried to make a basic program where a program asks for a word, then counts the letters in said word. It then tells asks if you want to know the letter in any given position of the letter. Im making this because I thought I would learn better if I just tried making something basic rather than endlessly watching videos on it.
I ran into a problem with the asking the user part of the code. I want to have it check whether the user typed Y or N, and if neither, repeat asking until either Y or N is inputted. I tried using goto, but I could not get it to work despite checking online tutorials on how it should work. If anyone could help that would be greatly appreciated :).
When run, it does the following: enter image description here
The code is below, thank you for reading:
#include <string>
using namespace std;
int main(){
string text; //variable for the word to be measured
int letter; //variable for the placement of the letter in word
string confirmation; //variable for Y or N
cout << "This program counts letters in a word \n\n";
cout << " Please type a word for me to count: \n\n";
cin >> text;
cout << "\nYour word has " << text.length() << " letter";
if (text.length()>1){
cout << "s"; // Checks whether to put an s at the end of the prev. sentence for a plural or not
}
cout << "\n\nThis is what you typed by the way: " << text << "\n\n";
cout << "Would you like me to find the letter in any given position in the word? \n\n If yes, type Y. If no, type N: \n\n";
cin >> confirmation;
check:
if (confirmation == "Y"){ //Loops until one of these are fulfilled
cout << "What position's letter would you like me to find? \n\n";
cin >> letter;
cout << "\n" << text[letter-1] << "\n\n";
cout << "Thanks for using me, have a nice day";
} else if (confirmation == "N"){
cout << "\nAlright have a nice day";
} else {
goto check;
}
return 0;
}
First, goto-Syntax is something you do not need to learn as a beginner. In 99.99% there are better alternatives than using goto, so until you are very advanced, just pretend that goto does not exist in C++.
Second, the goto in your code works. It is just that if the user answers something different than "Y" or "N", your code will infinitely loop between the label check: and the goto check statement, as there is no way that confirmation can change in between.
Last, here is an example how to better do this, using a while-loop.
cout << "Would you like me to find the letter in any given position in the word? \n\n If yes, type Y. If no, type N: \n\n";
cin >> confirmation;
while (confirmation != "Y" && confirmation != "N") { //Loops until one of these are fulfilled
cout << "Please answer Y or N.\n";
cin >> confirmation;
}
if (confirmation == "Y"){
cout << "What position's letter would you like me to find? \n\n";
cin >> letter;
cout << "\n" << text[letter-1] << "\n\n";
cout << "Thanks for using me, have a nice day";
} else {
cout << "\nAlright have a nice day";
}

How to block user input entirely in C++ (UNIX)

I'm working on a project where I want to have delays in the output in C++ on UNIX. Here's an example of what I'm talking about:
cout << "You walk through the darkness, no sign of life in sight" << endl;
usleep(1000000);
cout << "What would you like to do?" << endl;
cin >> userCommand;
Now, if the user types something while the usleep is ongoing, it goes into the cin statement later, which, while I can give appropriate error messages, I'd rather not deal with. Additionally, sometimes I want certain things on the screen, so I don't want the user to just hold down enter and clear the screen.
Is there any command which fully blocks user input from even interacting with the screen? Something that I could deactivate right before my cin statement and reactivate right after the cin statement?
Thanks!
you can use
#include <stdio.h>
...
cout << "You walk through the darkness, no sign of life in sight" << endl;
getch();
cout << "What would you like to do?" << endl;
cin >> userCommand;
getch() block until you press a key

Do-while loop issue: Try to develop a simple game

Well, I'm writing to make a dice game. I tried searching dice game here but none of it seems to answer my question. This isn't a problem about the dice roll thing anyway. It's about the do while loop. I am very new to this site, I just found out about this via Maximum PC Magazine so please bear with me. Also I am new to programming.
Here is my code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
srand(time(NULL));
int userRoll = rand() % 6 + 1 ;
int computerRoll = rand() % 6 + 1 ;
string yesOrNoChoice;
string commandToThrowDie;
do{
cout << "Please enter \"throw\" (lowercase) to roll the die: ";
cin >> commandToThrowDie;
} while(commandToThrowDie != "throw");
do{
cout << "You rolled: " << userRoll << endl
<< "The Computer rolled: " << computerRoll << endl;
if (userRoll < computerRoll){
cout << "You lose. Try again? [Yes/No]: ";
}
if (computerRoll < userRoll){
cout << "You win! Try again? [Yes/No]: ";
}
if (computerRoll == userRoll) {
cout << "It's a draw. Try again? [Yes/No]: ";
}
cin >> yesOrNoChoice;
} while(yesOrNoChoice != "Yes");
system ("pause");
return 0;
}
The problem is that after asking the user to enter a choice at the end of the do-while-loop the program exits loop no matter what I enter, instead of looping back to another throw of the die.
It ends up like this:
I copied your code and it compiled and ran perfectly. Doesn't make sense exactly, but no issues. I say it doesn't make sense since when "Yes" is entered that is what kills it. I believe what you want it while(yesOrNoChoice == "Yes"). Perhaps having it as != was making you think you were getting the wrong behavior? Also, you should be using if, else if, else statements, not just if.

Using do while loop and while loop to write a program that will run random guessing game...i stuck at the do while loop

I have been run a random guessing game. The game secret numbers is from min to max that input by user, the guesser is ask guess the secret number and at the end is supposed to be asked if they would like to play again. There also has to be multiple options for print outs if the guesser is to high or low. Anyways, I want it to check and make sure that the user is inputting numbers, not something silly. So I have been going in circles trying to figure this part out. I am sure it is a easy fix, but I am new to programming and this has got me stumped. Any help would be appreciated.
my code should similar to below output images :
[1]http://i62.tinypic.com/wjvuqb.png
[2]http://i57.tinypic.com/2nq9jwm.png
[3]http://i62.tinypic.com/210zss7.png
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int min, max, secret=0, deposit, bet, guess;
bool again= true;
string name;
char reply;
cout<< setw(80)<< setfill('=')<<"\n\n";
cout<< setw(45)<< "NUMBER GUESSING GAME!"<<"\n\n";
cout<< setfill('=')<< setw(80)<<"\n\n";
cout<< "What ur name?\n";
getline(cin,name);
Again:
cout<< "Pls enter the min & max number\n";
while(!(cin>>min)||min<0)
{
cout<<"Min? ";
cin.clear();
cin.ignore();
}
while(!(cin>>max)||max<0)
{
cout<<"Max? ";
cin.clear();
cin.ignore();
}
while(!(max> min))
{
cout<<"Min is larger than Max\n";
goto Again;
}
cout<< "\nMin: "<<min<<"\nMax: "<<max<<"\n";
secret= rand() % max+min;
cout<<"Enter ur deposit: ";
cin>> deposit;
AA: cout<< setw(45)<< "\n\n\n\nRULES OF THE GAME"<<"\n\n";
cout<< setfill('-')<< setw(80)<<"\n\n";
cout<< "Guess number between "<< min<< " to "<< max;
cout<< "\nIf ur guess match, 10 times ur deposit!!";
cout<< "\nIf ur guess mismatch, lose ur betting amount!!";
cout<< "\n\n"<< setfill('-')<< setw(80)<<"\n\n\n";
cout<< "Current Balance: "<<deposit;
cout<< "\nWhat is ur betting amount? ";
cin>> bet;
do{
cout<< "\n\nEnter a guess to bet: ";
cin >> guess;
if (guess > max)
{
cout << "Too high!\n\n";
cin.clear();
cin.ignore();
}
else if (guess < min)
{
cout << "Too low!\n\n";
cin.clear();
cin.ignore();
}
}while (guess != secret);
if(guess != secret){
deposit-=bet;
cout << "\nThat's it! You got it!\n";
cout<<"Sorry, U lose RM "<< bet;
}
else{
bet*=10;
deposit+=bet;
cout << "\nThat's it! You got it!\n";
cout<<"Congratulation! U earn RM "<< bet;
}
cout<<"\n\nThe secret number was : "<< secret;
cout<< "\n\n\tCurrent Balance: "<<deposit<< "\n\n\n";
do{
cout<< "Wanna play again (y/n)? ";
cin>> reply;
if( reply=='y'){
again= true;
goto AA;
}
else
cout<<"\nReally? Ok, try again! ";
cin>>reply;
}while(again==false && reply=='n');
if(reply=='n'){
cout<<"\n\n\n"<< setw(80)<< setfill('+')<<"\n\n";
cout<< setw(30)<< "THX FOR PLAYING! UR CURRENT BALANCE IS RM "<< deposit<<"\n\n";
cout<< setfill('+')<< setw(80)<<"\n";
}
return 0;
}
You are using goto, and if you are using goto, raptors will tear you to pieces. Do not, under any circumstances use goto!
But you can use functions to make your code a bit clearer. This wall of text and copy paste is really hard to read.
First of all the formula you are using to calculate the random number is wrong. Suppose that min is 10, and max is 12. Then the rand() % max could be, let's say, 10. Adding min (10), the number to guess would be 20 - far greater than max... It should be secret = rand() % (max-min +1) + min; (if your interval is [min, max]).
Now to your question - as far as I understood you want to know if the entered guess is a number. Here is what you can do:
while(1)
{
cin >> guess;
if(cin){
if (guess > max){
cout << "Too high!\n\n";
cin.clear();
cin.ignore();
continue;
}
else if (guess < min){
cout << "Too low!\n\n";
cin.clear();
cin.ignore();
continue;
}
else if(guess != secret){
deposit-=bet;
cout<< "Sorry, U lose RM "<< bet;
}
else if(guess == secret){
bet*=10;
deposit+=bet;
cout<< "\n\nCongratulation! U earn RM "<< bet;
}
break;
}
else
{
cin.clear();
cin.ignore();
cout << "Error! You did not enter a number!" << endl;
continue;
}
}
If the user didn't enter a number, the cin's fail flag will be up and you can use that.
Also, when trying again (goto AA;) you do not compute the random value again and you should. In order to get a different sequence of random numbers from rand() every time you start the program, you should seed the random generator from the current time. In the beginning of main, put srand((unsigned int)time(NULL)); What this does is that it gives the random generator a number and on its base it will generate random numbers. If the number is the same every time the program is started, the same numbers will be generated. But given the always changing current time, every time the sequence will be different.
Using goto can make your code very messy and can make bugs very hard to notice. Yes, it is a part of the language and it is there to be used, but one should be very careful with it. Especially if you are new to programming, try to refrain from using it. You could use while(1) or for(;;) if you need endless loops - you can get to the next iteration with continue; and stop them with break;.
Something is also wrong with the guessing loop. It seems that you cannot lose. You should decrease the deposit in the while loop and check if it is 0.
Edit: In the edited code you can see that whenever the user needs to enter the number again, you just skip the iteration with continue. This is also an example how you should deal with endless loops instead of using goto. With practice, you will get he hang of it. ;)
Edit 2:
do{
cout<< "Wanna play again (y/n)? ";
cin>> reply;
if( reply!='y'&& reply!='n')
cout<< "\nReally? Ok, try again! \n";
}while(reply!='n' && reply!='y');
if( reply =='y')
goto AA;
if(reply=='n'){
cout<< "\n\n\n"<< setw(80)<< setfill('+')<< "\n\n";
cout<< setw(30)<< "THX FOR PLAYING! UR CURRENT BALANCE IS RM "<< deposit<< "\n\n";
cout<< setfill('+')<< setw(80)<< "\n";
}
This should make the reply cycle work. Your program should consist of different chunks of code for different purposes, and in this cycle you mixed up checking the correctness of the answer with what will happen if the answer is correct. It's easier first to do the first, and then to do the second thing. Using functions can generally help you with this.
Edit 3: In that new code you have a lot of problems with if statement. Firstly, what is !> ? I think you meant < or <= , !> does not exist, it won't even compile. Another thing - what happens when max or min is 0? You haven't covered that.
You use if-else chains a lot and in this case it is not necessarily needed. For example you don't need if(min>0) , you don't even need the else before it. If you don't enter one of the if statement - the input is correct and you can break, if you enter one of them - it has continue; in it and the code below is not executed. The same goes for the last if statement in the max if-else chain executed if the input is a number.
Anyway, you could do it a lot simpler. For example the min loop can be:
cout << "Pls enter the min of secret number\n";
while (!(cin >> min) || min<=0){
cout << "Pls enter the min of secret number\n";
cin.clear();
cin.ignore();
}
You could see that this will work if you realize that you should break if (cin && min>0). Now when you negate that in order to place it as the while condition it becomes (!cin || min<=0).
Anyway, I didn't see any other problem in the code, I tested it and it worked. And now without goto it looks a lot better.

Need help fixing strange cin behavior

I'm building a product checkout piece of software and I keep hitting a strange bug. I have a central menu that gets user input. After a function is finished with its task, it sends the user back to the menu. For certain functions, however, the cin.get() I have after the menu prompt bugs out and won't accept the first command given. Here are the relevant code fragments:
The main menu loop:
bool foreverLoopFlag = true;
while (foreverLoopFlag) {
cout << "\nC[heckout], R[eturn], S[tudent], P[roduct], Q[uit]. Choice? ";
cin.get(actionChoice);
std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
cout << endl;
actionChoice = toupper(actionChoice);
switch (actionChoice) {
case 'C':
checkoutSoftware(studentMap, productList);
break;
case 'R':
returnSoftware(studentMap, productList);
break;
case 'S':
studentDisplay(studentMap, productList);
break;
case 'P':
productDisplay(studentMap, productList);
break;
case 'Q':
foreverLoopFlag = false;
break;
default:
cout << "Invalid command.\n";
break;
}
}
A problem-child function, studentDisplay:
void studentDisplay(map<string, Student> & studentMap, list<Product> & productList) {
string inputCLID;
cout << "Please enter student CLID: ";
cin >> inputCLID;
if (studentMap.find(inputCLID) != studentMap.end()) {
cout << "\nStudent: " << studentMap[inputCLID].name << " (" << inputCLID << ")\n";
cout << "\tBorrowed items: " << endl;
for (list<Student::LentProduct>::iterator it = studentMap[inputCLID].checkedOut.begin();
it != studentMap[inputCLID].checkedOut.end(); it++) {
cout << "\t\tProduct: " << (*it).name;
cout << "\tDue Date: " << (*it).dateDue << endl;
}
} else {
cout << "\nError: CLID not in database.\n";
}
}
Some of the indention was mangled moving over to SE, I apologize. Here an example of the issue I'm having:
C[heckout], R[eturn], S[tudent], P[roduct], Q[uit]. Choice? s
Please enter student CLID: mrx8394
Student: Mark Xeno (mrx8394)
Borrowed items:
Product: Bluebeard Due Date: 12/14/2013
C[heckout], R[eturn], S[tudent], P[roduct], Q[uit]. Choice? c
Invalid command.
C[heckout], R[eturn], S[tudent], P[roduct], Q[uit]. Choice? q
I tried putting a std::cin.flush() at the beginning of the menu-loop, but that didn't work. I tried doing std::cin.ignore(std::INT_MAX) at the beginning of the menu-loop, but that makes it to where the menu never even shows up. I also tried a std::cin.sync(), but that just makes an infinite cycle of this:
C[heckout], R[eturn], S[tudent], P[roduct], Q[uit]. Choice?
Please enter a product to checkout:
Error: No such product.
I have no idea where to go from here. I know it is probably just some quirk of the iostream that I'm not picking up on. Any assistant would be appreciated.
EDIT: I do not have enough reputation to upvote or comment on specific answers (all of my rep is on Math.SE!!!), so I'll comment here. #Igor-tandetnik 's solution worked perfectly. I had moved everything else over to a getline, but I suppose that guy just got left in the shuffle. My thanks come in droves.
#qwrrty While it may be folly, I had a specification to meet (don't you just love low level University courses). I don't typically ask for help debugging assignments, but this was the last bug and my knowledge of iostream isn't that deep, but I knew someone on here would know what was bugging out my stream state.
Thanks again guys, cheers!
cin >> inputCLID reads characters up to, but not including, the first whitespace character (in your example, a line feed). That character is left in the stream. It is that character that cin.get(actionChoice) later retrieves.
I tend to think that for interactive input, trying to use stdin and/or cin for reading anything other than a full line of input is folly. There are just too many ways for your program to get confused about what's still on the input stream, and end up in an unrecoverable state.
At the very least I'd modify the program to say what command it thinks is invalid, or product that doesn't exist:
default:
cout << "Invalid command '" << actionChoice << "'\n";
and
cout << "Error: No such product '" << productChoice << "'\n";
That way at least you can get an idea of what input the program is actually using for these variables.