I have this C++ code and I am trying to do the following:
Prompt the user to enter "p" to play or "q" to quit, if the user enters anything "p" the program will continue, if the user enters "q" program would just terminate and if they entered an invalid input, it would also terminate. How do I do that?.
Thank you,
Here is the code:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int Umain = 0;
double Atemp = 0;
double Utemp = 0;
double Working = 0;
double Total = 0;
char Answer = 'x';
void displayOverview ();
void playOrQuit();
void promptNumber();
int main(){
displayOverview();
playOrQuit();
promptNumber();
return 0;
}
void displayOverview(){
}
void playOrQuit(){
string playOrNot;
cout << "If you want to play please press 'p' for play, and 'q' if you wish to quit\n";
cin >> playOrNot;
if(playOrNot == "p"){
cout << "Awesome, lets start playing !!! \n";
}if(playOrNot == "q"){
cout << "Alright then, see you soon !!\n";
}
}
void promptNumber(){
do{
cout << "Please Enter numbers between 1 and 12: ";
cin >> Umain;
cout << "\n";
for (Utemp = Umain; Utemp > 0; Utemp--)
{
cout << "Please enter a number: ";
cin >> Atemp;
Working = (Working + Atemp);
}
}while (Answer == 'y');
}
Just add a call to exit after you detect 'q' was pressed:
}if(playOrNot == "q"){
cout << "Alright then, see you soon !!\n";
exit(0); // <=== Add this here
Exiting with a 0 traditionally means the program exited in an expected fashion and without any errors.
The usual way to do this kind of thing is to have PlayOrQuit return a bool with true meaning "keep on playing" and false meaning "quit". Use that function to control a loop:
while (PlayOrQuit()) {
// game logic goes here
}
That way you can put any appropriate cleanup code after the game loop instead of having a brute-force exit from down inside the function.
There are a couple of ways you can achieve this.
But I suggest you include the stdlib.h library and use system("exit") right inside your else statements that is meant to exit the program.
Add end(), return 0 or exit(0).
Use u brain like, if you need this then i will remember nearest possible thing you spot from past.
So you never made these kind of mistake.
}if(playOrNot == "q"){
cout << "Alright then, see you soon !!\n";
exit(0);
}
Related
Please note that I am a complete beginner at C++. I'm trying to write a simple program for an ATM and I have to account for all errors. User may use only integers for input so I need to check if input value is indeed an integer, and my program (this one is shortened) works for the most part.
The problem arises when I try to input a string value instead of an integer while choosing an operation. It works with invalid value integers, but with strings it creates an infinite loop until it eventually stops (unless I add system("cls"), then it doesn't even stop), when it should output the same result as it does for invalid integers:
Invalid choice of operation.
Please select an operation:
1 - Balance inquiry
7 - Return card
Enter your choice and press return:
Here is my code:
#include <iostream>
#include <string>
using namespace std;
bool isNumber(string s) //function to determine if input value is int
{
for (int i = 0; i < s.length(); i++)
if (isdigit(s[i]) == false)
return false;
return true;
}
int ReturnCard() //function to determine whether to continue running or end program
{
string rtrn;
cout << "\nDo you wish to continue? \n1 - Yes \n2 - No, return card" << endl;
cin >> rtrn;
if (rtrn == "1" and isNumber(rtrn)) { return false; }
else if (rtrn == "2" and isNumber(rtrn)) { return true; }
else {cout << "Invalid choice." << endl; ReturnCard(); };
return 0;
}
int menu() //function for operation choice and execution
{
int choice;
do
{
cout << "\nPlease select an operation:\n" << endl
<< " 1 - Balance inquiry\n"
<< " 7 - Return card\n"
<< "\nEnter your choice and press return: ";
int balance = 512;
cin >> choice;
if (choice == 1 and isNumber(to_string(choice))) { cout << "Your balance is $" << balance; "\n\n"; }
else if (choice == 7 and isNumber(to_string(choice))) { cout << "Please wait...\nHave a good day." << endl; return 0; }
else { cout << "Invalid choice of operation."; menu(); }
} while (ReturnCard()==false);
cout << "Please wait...\nHave a good day." << endl;
return 0;
}
int main()
{
string choice;
cout << "Insert debit card to get started." << endl;
menu();
return 0;
}
I've tried every possible solution I know, but nothing seems to work.
***There is a different bug, which is that when I get to the "Do you wish to continue?" part and input any invalid value and follow it up with 2 (which is supposed to end the program) after it asks again, it outputs the result for 1 (continue running - menu etc.). I have already emailed my teacher about this and this is not my main question, but I would appreciate any help.
Thank you!
There are a few things mixed up in your code. Always try to compile your code with maximum warnings turned on, e.g., for GCC add at least the -Wall flag.
Then your compiler would warn you of some of the mistakes you made.
First, it seems like you are confusing string choice and int choice. Two different variables in different scopes. The string one is unused and completely redundant. You can delete it and nothing will change.
In menu, you say cin >> choice;, where choice is of type int. The stream operator >> works like this: It will try to read as many characters as it can, such that the characters match the requested type. So this will only read ints.
Then you convert your valid int into a string and call isNumber() - which will alway return true.
So if you wish to read any line of text and handle it, you can use getline():
string inp;
std::getline(std::cin, inp);
if (!isNumber(inp)) {
std::cout << "ERROR\n";
return 1;
}
int choice = std::stoi(inp); // May throw an exception if invalid range
See stoi
Your isNumber() implementation could look like this:
#include <algorithm>
bool is_number(const string &inp) {
return std::all_of(inp.cbegin(), inp.cend(),
[](unsigned char c){ return std::isdigit(c); });
}
If you are into that functional style, like I am ;)
EDIT:
Btw., another bug which the compiler warns about: cout << "Your balance is $" << balance; "\n\n"; - the newlines are separated by ;, so it's a new statement and this does nothing. You probably wanted the << operator instead.
Recursive call bug:
In { cout << "Invalid choice of operation."; menu(); } and same for ReturnCard(), the function calls itself (recursion).
This is not at all what you want! This will start the function over, but once that call has ended, you continue where that call happened.
What you want in menu() is to start the loop over. You can do that with the continue keyword.
You want the same for ReturnCard(). But you need a loop there.
And now, that I read that code, you don't even need to convert the input to an integer. All you do is compare it. So you can simply do:
string inp;
std::getline(std::cin, inp);
if (inp == "1" || inp == "2") {
// good
} else {
// Invalid
}
Unless that is part of your task.
It is always good to save console input in a string variable instead of another
type, e.g. int or double. This avoids trouble with input errors, e.g. if
characters instead of numbers are given by the program user. Afterwards the
string variable could by analyzed for further actions.
Therefore I changed the type of choice from int to string and adopted the
downstream code to it.
Please try the following program and consider my adaptations which are
written as comments starting with tag //CKE:. Thanks.
#include <iostream>
#include <string>
using namespace std;
bool isNumber(const string& s) //function to determine if input value is int
{
for (size_t i = 0; i < s.length(); i++) //CKE: keep same variable type, e.g. unsigned
if (isdigit(s[i]) == false)
return false;
return true;
}
bool ReturnCard() //function to determine whether to continue running or end program
{
string rtrn;
cout << "\nDo you wish to continue? \n1 - Yes \n2 - No, return card" << endl;
cin >> rtrn;
if (rtrn == "1" and isNumber(rtrn)) { return false; }
if (rtrn == "2" and isNumber(rtrn)) { return true; } //CKE: remove redundant else
cout << "Invalid choice." << endl; ReturnCard(); //CKE: remove redundant else + semicolon
return false;
}
int menu() //function for operation choice and execution
{
string choice; //CKE: change variable type here from int to string
do
{
cout << "\nPlease select an operation:\n" << endl
<< " 1 - Balance inquiry\n"
<< " 7 - Return card\n"
<< "\nEnter your choice and press return: ";
int balance = 512;
cin >> choice;
if (choice == "1" and isNumber(choice)) { cout << "Your balance is $" << balance << "\n\n"; } //CKE: semicolon replaced by output stream operator
else if (choice == "7" and isNumber(choice)) { cout << "Please wait...\nHave a good day." << endl; return 0; }
else { cout << "Invalid choice of operation."; } //CKE: remove recursion here as it isn't required
} while (!ReturnCard()); //CKE: negate result of ReturnCard function
cout << "Please wait...\nHave a good day." << endl;
return 0;
}
int main()
{
string choice;
cout << "Insert debit card to get started." << endl;
menu();
return 0;
}
I'm super new to this, and am trying to code a simple shop interface for a CLI adventure game.
The problem I'm having is in between uses of cin.get(). I've read another post but don't understand what's being said. Can someone explain like I'm 5?
I use cin.get() once in the MainMenu() to wait for Enter to continue. This punishes the player's health if they do anything other than press Enter.
I then move forwards to the Introduction(), where I'm trying to pull the same trick, but it carries the input from cin.get() from the MainMenu() function.
The other code in main() is just keeping track of the character's health and stopping the program if it reaches 0 by way of another function.
#include <iostream>
#include <ctime>
#include <string>
using namespace std;
int MainMenu()
{
cout << "\nPress the ENTER key\n";
char Input = cin.get();
if (Input == '\n')
{
return 0;
}
else if (Input != '\n')
{
cout << "I meant ONLY the ENTER key... Oh well its your health pool.\n";
CharHealth(-2);
cout << "You took 2 damage. \nYou now have " << CharHealth(0) << "Health.\n";
return 0;
}
}
int Introduction()
{
cout << "you awake in a puddle, walk to town. \nPress [ENTER]";
char Input = cin.get();
if (Input != '\n')
{
cout << "\nfor real?\nTake Another 2 Damage\nwhat did you think?... Idiot" ;
CharHealth(-2);
return 0;
}
else
{
return 0;
}
}
int main()
{
MainMenu();
Introduction();
while (CharHealth(0) > 0)
{
cout << "winner";
return 0;
}
cout << "\n You died. idiot.";
return 0;
}
Don't judge my story telling, everything is still placeholders right now.
My console just reads:
Press the ENTER key
asdf
I meant ONLY the ENTER key... Oh well its your health pool.
You took 2 damage.
You now have 1Health.
you awake in a puddle, walk to town.
Press [ENTER]
for real?
Take Another 2 Damage
what did you think?... Idiot
You died. idiot.
C:\Users\KR's\Documents\text Shop>
cin.get() reads 1 char at a time. So, for example, if the user types in asdf, then the next cin.get() will read and return a, leaving sdf in cin's input buffer. Then the next cin.get() will read and return s, leaving df in cin's input buffer. And so on. Your code is not taking that into account. There is only 1 input buffer in cin, there is no per-function input buffer, like you are expecting.
If the user does not type in what you want, use cin.ignore() to discard the unwanted input. For example:
...
#include <limits>
...
int MainMenu()
{
cout << "\nPress the ENTER key\n";
char Input = cin.get();
if (Input != '\n')
{
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // <-- ADD THIS
cout << "I meant ONLY the ENTER key... Oh well its your health pool.\n";
CharHealth(-2);
cout << "You took 2 damage. \nYou now have " << CharHealth(0) << "Health.\n";
}
return 0;
}
int Introduction()
{
cout << "you awake in a puddle, walk to town. \nPress [ENTER]";
char Input = cin.get();
if (Input != '\n')
{
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // <-- ADD THIS
cout << "\nfor real?\nTake Another 2 Damage\nwhat did you think?... Idiot" ;
CharHealth(-2);
}
return 0;
}
cin.get() reads only one character and leave other inputted things on the stream.
It seems you want to read until \n is read. It can be done like this:
int MainMenu()
{
cout << "\nPress the ENTER key\n";
int count = 0;
while (cin.get() != '\n') count++;
if (count == 0)
{
return 0;
}
else if (count != 0) // we won't need this if statement, but I respect you
{
cout << "I meant ONLY the ENTER key... Oh well its your health pool.\n";
CharHealth(-2);
cout << "You took 2 damage. \nYou now have " << CharHealth(0) << "Health.\n";
return 0;
}
}
(warning: This code will fail into an infinite loop if we get EOF before newline)
I am in the begining steps to answer a Lottery HW problem, however, when I call the getLottoPicks function it throws off the program with an 11db error. So when the program first runs and you exit with 'q' or 'Q' it works, but if the user goes thru the program once and then tries to quit I get the 11db error. I tried sticking cin.ignore() in all sorts of places but that didn't help.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <cctype>
using namespace std;
void menu();
int getLottoPicks(int[], int);
int main()
{
char choice;
const int SIZE = 6;
int UserTicket[SIZE];
int WinningNums[SIZE];
string name;
do
{
menu();
cin >> choice;
cout << endl;
cin.ignore();
switch (choice)
{
case '1':
cout << "Please enter your name: ";
getline(cin, name);
getLottoPicks(UserTicket,SIZE);
for(int i = 0; i <= SIZE; i++)
{
cout << UserTicket[i];
cout << ", ";
}
cout << endl <<endl;
break;
case 'q':
case 'Q':
cout << "You have chosen to quit the program. Thank you for using!\n";
break;
default:
cout << "Invalide Selection.\n";
break;
}
}while (choice != 'q' && choice != 'Q');
return 0;
}
void menu()
{
cout << "1) Play Lotto\n";
cout << "q) Quit Program\n";
cout << "Please make a selection: \n";
}
int getLottoPicks(int nums[], int size)
{
cout << "Please enter your 7 lotto number picks between 1 and 40.\n";
for(int i = 0; i <= size; i++)
{
cout << "Please pick #" << i + 1 << ": ";
cin >> nums[i];
cout << endl;
}
return nums[0], nums[1], nums[2], nums[3], nums[4], nums[5], nums[6];
}
/* Here is a run thru of the program
1) Play Lotto
q) Quit Program
Please make a selection:
1
Please enter your name: asdf
Please enter your 7 lotto number picks between 1 and 40.
Please pick #1: 1
Please pick #2: 1
Please pick #3: 1
Please pick #4: 1
Please pick #5: 1
Please pick #6: 1
Please pick #7: 1
1, 1, 1, 1, 1, 1, 1,
1) Play Lotto
q) Quit Program
Please make a selection:
q
You have chosen to quit the program. Thank you for using!
(11db) <----- this is what I am getting in green color. and the program doesn't quit until i manually close it with Cmd .
*/
(lldb) is the command prompt for the LLDB debugger, not an error code. Your program has crashed, probably because you're loading 7 elements into an array of size 6.
The problem is in the function getLottoPicks.
First to point a design problem: you are somehow calling this function to get 7 inputs from the user but you are mistakenly returning 7 elements from the parameter nums (which in your case is causing the function to access the 7th element from an array that only contains 6 elements). Besides that you are already getting the values by storing the them in the nums parameter. Change the getLottoPicks return type to void and delete the return nums[0], nums[1], nums[2], nums[3], nums[4], nums[5], nums[6]; line.
Secondly you are using the condition to exit the for loops wrong. Arrays in C++ are accessed by indexes starting with 0. When you state the exit condition to a for loop to exit when the iterator becomes <= than the array size, you are actually making the code to cause a stack overflow problem when execute (it will write to the array variable beyond its boundaries). In the case of your code, change the <= operator to < in the for loop inside the getLottoPicks.
I am currently working on a text based adventure game as a project for class. I have mostly everything started and working fine. The only problem is when I ask the user which room they want to change to, if they enter a blank input, then a message should output saying "You must choose a room." For the life of me I cannot figure it out. Any help is much appreciated.
Code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
bool game_play = true;
bool game_start = true;
int room_change;
int room_current = 0;
while (game_play == true) {
if (game_start == true) {
srand((unsigned int)time(NULL));
room_change = rand() % 2 + 1;
game_start = false;
}
else {
for (bool check = false; check == false;) { // Check if input is invalid
cin >> room_change;
if (cin.fail()) {
cout << "Choose an existing room.";
cin.clear();
cin.ignore();
}
else if (room_change == room_current) {
cout << "You're already in that room.";
}
else {
check = true;
}
}
}
switch (room_change) {
case 1:
cout << "You are in room 1.";
room_current = 1;
break;
case 2:
cout << "You are in room 2.";
room_current = 2;
break;
case 3:
game_play = false;
break;
default:
cout << "That room doesn't exist.";
}
}
return 0;
}
I just ran your code and when you hit enter, it will keep waiting until you enter a number or something invalid such as a character or a string. I did find that if you change your code from
cin >> room_change;
to
cin >> noskipws >> room_change;
when the user inputs a blank, it will cause the cin.fail() to return true and then proceed to print "Choose an existing room."
In your situation, the while loop will keep getting called until we have valid input. The "Choose an existing room" does get repeated because room_change is an integer, so when we hit enter, the '\n' will be left in the buffer. The while loop on the next iteration then reads that '\n' and executes the cin.fail() before letting you input something else. One solution I found is to use more cin.ignore() statements.
for (bool check = false; check == false;) { // Check if input is invalid
cin >> noskipws >> room_change;
if (cin.fail()) {
cout << "Choose an existing room.";
cin.clear();
cin.ignore();
} else if (room_change == room_current) {
cout << "You're already in that room.";
cin.ignore();
} else {
check = true;
cin.ignore();
}
}
The reason is because we want to get rid of that '\n' so that the cin.fail() does not execute. However, I did find that when you input a character, it will print "Choose an existing room" twice. It will print the first time because a character is not an integer, and a second time because of that '\n'.
The only problem is when I ask the user which room they want to change to, if they enter a blank input, then a message should output saying "You must choose a room."
Using std::getline and then extracting the number from the line using a std::istringstream is a better strategy for that.
std::string line;
std::cout << "Choose an existing room. ";
while ( std::getline(std::cin, line) )
{
// Try to get the room_change using istringstream.
std::istringstream str(line);
if ( str >> room_change )
{
// Successfully read the room.
break;
}
// Problem reading room_change.
// Try again.
std::cout << "Choose an existing room. ";
}
#include <iostream>
using namespace std;
int main(){
int room_change=200;
cout<<"Enter Blank";
cin>>room_change;
if(room_change==NULL){
cout<<"There is NO-THING"<<endl;
}
if(room_change!=NULL){
cout<<"There is something and that is :"<<room_change<<endl;
}
return 0;
}
But a much simpler approach to this would be to use Strings. If this is a Homework of sort and you are limited to Integer variable only. Its much more complicated if you want to detect if an Buffer is empty or not. Regardless of homework limitation, the OS layer input is String based. How can I use cin.get() to detect an empty user input?
I just started with c++ (coming from java) and I'm trying to do some basic exercises. The idea is to ask for any input other than 5, if the user inputs 5, display a message, and if the user inputs anything other than 5 ten times, display another message. Here's the code:
void notFive () {
int count = 0;
while (count < 10) {
int input = 0;
cout << "Enter any number other than 5." << endl;
cin >> input;
if (input == 5)
break;
count++;
}
if (count == 10)
cout<<"You are more patient than I am, you win.";
else
cout << "You weren't supposed to enter 5!";
}
}
My problem is that all this code does is print out "Enter any number other than 5." 10 times, then say "You are more patient that I am, you win." any ideas what is wrong?
if you guys want all my code (to make sure I'm not just being an idiot) here it is:
#include <iostream>
#include <stdio.h>
using namespace std;
class Hello {
public:
void notFive () {
int count = 0;
while (count < 10) {
int input = 0;
cout << "Enter any number other than 5." << endl;
if ( ! (cin >> input) ) {
cout << "std::cin is in a bad state! Aborting!" << endl;
return;
}
if (input == 5)
break;
count++;
}
if (count == 10)
cout<<"You are more patient than I am, you win.";
else
cout << "You weren't supposed to enter 5!";
}
}hello;
int main() {
Hello h;
h.notFive();
return 0;
}
Your code works perfectly for me (in Visual Studio 2012) when I change notFive to main. Your problem must lie outside this code (possibly because cin is in a broken state, as others have suggested).
Change this line:
cin >> input
To this:
if ( ! (cin >> input) ) {
cout << "std::cin is in a bad state! Aborting!" << endl;
return;
}
The behavior you describe is what would happen if Something Bad happened to cin before this code was run.
Edit:
Add this same code to earlier uses of cin to find out where it's entering a bad state.
An example of this happening would be if the code tried to read an int, and the user typed a letter of the alphabet.
You can also call cin.clear(); to restore the working state of cin.
Here are my comments:
fflush(stdin) is not valid. The stdin cannot be flushed. Also,
this may not be the same input as cin.
You need to check for cin.fail after cin >> input. If I enter a
letter, your input statement will fail.