Problems using the cin object

in my final project, a poker simulator and a black jack, my main function does not seem to want cin to work. The whole project is a syntax error, so this is not a problem, but in order to check if it works or not, I need a β€œcin” to work. The following is my main function when I have problems:

#include <iostream> using namespace std; #include "card.h" #include "poker.h" #include "blackJack.h" void handlePoker(int&); void handleBlackJack(int&); //TO DO: //FIX CIN PROBLEM //*pulls hair out* //main function: //asks the user what game they want to play //then calls a function for the appropriate //game chosen int main() { //two choices: //one for quitting the program //the other for whichever game they want char yesOrNo; char choice; int totalMoney; cout<< "please enter a starting amount to bet with"<<endl; cin>> totalMoney; do{ //ask the user which game they want cout<<"would you like to play poker or black jack?"<<endl; cout<<"input '1' for poker and '0' for blackjack"<<endl; cin>>choice; if(choice == '1') { handlePoker(totalMoney); } else if(choice == '0') { handleBlackJack(totalMoney); } else { cout<<"I'm sorry, the input you entered was invalid"<<endl; cout<<"please try again"<<endl; } cout<<"would you like to try again?"<<endl; cout<<"('y' for yes, or 'n' for no)"<<endl<<endl; cin>>yesOrNo; }while(yesOrNo == 'y' || yesOrNo == 'Y'); } 

Every time I use "cin" in a do while loop, it doesn't let me type anything. A program never stops for user input. like not, it outputs the program:

 "please enter a starting amount to bet with" *user can enter starting amount here, this "cin" works no problem* "input '1' for poker and '0' for black jack" "I'm sorry, the input you entered was invalid" "please try again" "would you like to try again?" "('y' for yes, or 'n' for no) 

then the program ends because none of the options has any meaning in them. I will include more code if asked, but I believe this is the problem. Thanks to everyone who can help me!

edit: the program does enter a do while loop, and all messages are printed as they should be, but the program does not allow me to enter any data at all, it does not stop me from entering data, it just acts as if it does not exist.

+4
source share
2 answers

Usually, when I see cin ignoring everything and putting me in an infinite loop, which occurs when I enter an invalid input and never clear the state of the stream. Namely, entering β€œA” for the number will do this. The idiomatic way to do this would be something like

 while (! (cin >> totalMoney)) { cout<<"I'm sorry, the input you entered was invalid"<<endl; cout<<"please try again"<<endl; cin.clear(); //important } // totalMoney holds a valid value now 
+4
source

Try using cin.ignore (), not just cin for the process of waiting for user input

 cin>>choice; cin.ignore(); 

Refer this link on MSDN for more information.

0
source

Source: https://habr.com/ru/post/1384960/


All Articles