problems with using the "cin" object - c++

in my final project, a poker and black jack simulator, my main function doesn't appear to want "cin" to work. The entire project is syntax error free, so that's not a problem, but in order to test to see if it runs or not, I need "cin" to work. The following is my main function, where I seem to be having the trouble:
#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');
}
Everytime I use "cin" in the do while loop, it won't let me input anything. The program never stops for user input.
as it is not, he's the program's output:
"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 choices have any value in them.
I'll include more code if asked, but I believe this is where the problem with it lies.
thank you to all who may help me!
edit: The program does enter the do while loop, and all messages are printed as they should bee, but the program won't let me input any data at all, it doesn't stop to let me input data, it just acts as if they do not exist.

Usually when I see cin ignoring everything and putting me in an infinite loop, that's caused when I enter in invalid input, and never clear the stream state. Namely, entering "A" for a number will do that. 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

Try using cin.ignore() instead of just cin for the process to wait for user input
cin>>choice;
cin.ignore();
Check out this link on MSDN for more info

Related

If you enter the desired input twice, it outputs twice?

Heres my example:
while (response == 'y')
{
playOneGame();
cout << "Great! Do you want to play again (y/n)? ";
cin >> response;
}
And if you type in: yy
It prints the output twice:
"Great! Do you want to play again (y/n)? Great! Do you want to play again (y/n)? "
I would just like to understand why. This program is written in C++ if that matters. Thanks.
Since you are comparing it to a char (result == 'y'), I'm assuming result is also a char.
The cin operation is going just read one char, and leave the second one on the input buffer. Then, the next time through the loop, it reads the second 'y' without any additional user input required.
If you want to be sure there is nothing left in the buffer, read until you get a line terminator. Or you can read into a string:
string response = "y";
// continues on anything that starts with lowercase 'y'.
// exits on anything else.
while (response.length() >= 1 && response[0] == 'y') // length check maybe unnecessary?
{
playOneGame();
cout << "Great! Do you want to play again (y/n)? ";
cin >> response;
}
It is not clear the type of response, but I assume it is char.
char response;
while(response=='y'){
playOneGame();
cout << "Great! Do you want to play again (y/n)? ";
cin >> response;
}
cin reads all the chars until you stop sending chars to it. Simply, cin gets whole terminal line so when you press 'yy', while loop runs twice.
If loop runs twice and prints the message two times:
1. It doesn't start game again.
2. Even, it starts the game, when it is over, for the second y, it does starts game again without asking.
Modify your code to read one char and continue. You can use getche() to get one char and continue.
This is exactly what you need. Apply the code below to your real case.
#include<iostream>
#include<limits>
using namespace std;
int main()
{
char response = 0;
while(cin >> response){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "You enterd: " << response << endl;
}
return 0;
}
Here is the explanation:
Why would we call cin.clear() and cin.ignore() after reading input?

My C++ Program wont accept inputs after the menu

I am doing a program for a class in school, and when I try to run the code I wrote below (only half of the project is done, but it's in a state where it should run anyways) the menu comes up fine, but then it jumps straight to the end of the program and wont let me input the important part..
When I remove the menu (which will be a necessity later when I finish the project) it works fine, but when it's there like I need it to be, it wont run properly
//Project 4 Written By Nate
#include <iostream>
#include <iomanip>
using namespace std;
int menuOption;
char stockName[21],symbol[10];
float openingPrice,closingPrice,numberShares,gain;
int main()
{
// MENU //
cout<<"Welcome to Project 4! Please select the program you would like to run:\n\n 1)Stock Program\n\nEnter your selection: ";
cin>>menuOption;
if(menuOption == 1) {
goto stockProgram;
} else
{
cout<<"Invalid response received. Program will now terminate";
return 0;
}
stockProgram:
cout<<"This program will ask you information about a stock you own.\n\n";
cout<<"Enter stock name: ";
cin.get(stockName,21);
cin.ignore(80,'\n');
cout<<"Symbol: ";
cin.get(symbol,10);
cin.ignore(80,'\n');
cout<<"Enter opening price: ";
cin>>openingPrice;
cout<<"Enter closing price: ";
cin>>closingPrice;
cout<<"Enter the number of shares: ";
cin>>numberShares;
cout<<"\n\n";
gain=(numberShares*closingPrice)-(numberShares*openingPrice);
cout<<setw(10)<<"Stock Name"<<setw(10)<<"Symbol"<<setw(10)<<"Opening"<<setw(10)<<"Closing"<<setw(10)<<"Shares"<<setw(11)<<"Gain\n";
cout<<setw(10)<<stockName<<setw(10)<<symbol<<setw(10)<<openingPrice<<setw(10)<<closingPrice<<setw(10)<<numberShares<<setw(10)<<gain<<"\n\n";
cout<<"=====================================================================\n";
cout<<" This gain could've been yours, too bad you are an anti-mac person.\n";
return 0;
}
Thanks..
You probably still have the a newline character or other characters after the 1 in the initial input. You've used cin.ignore on other inputs but not the first.
cout<<"Welcome to Project 4! Please select the program you would like to run:\n\n 1)Stock Program\n\nEnter your selection: ";
cin>>menuOption;
cin.ignore(80,'\n');
ignore will extract the delimiting \n
Also, whenever dealing with istream check that it was successful in getting the input into the correct type:
#include <limits>
#include <sstream>
int myVariable;
if( (cin >> myVariable).fail() )
{
// Error - input was not an integer
std::cerr << "Input was not an integer" << std::endl;
return -1;
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Adding cin.ignore() after cin>>menuOption- this will read the one int that currently resides within the buffer & discard it since the EOF is the new line after input.
int main()
{
// MENU //
cout<<"Welcome to Project 4! Please select the program you would like to run:\n\n 1)Stock Program\n\nEnter your selection: ";
cin>>menuOption; cin.ignore();
if(menuOption != 1) {
cout<<"Invalid response received. Program will now terminate";
return 0;
}
//etc
}

c++ checking whether input is a number [duplicate]

This question already has answers here:
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 7 years ago.
I am using netbean ide for c++ study
I would like to force the user to pick only number between 1 to 3
int displayMenu()
{
while(true)
{
cout<<"Please choose one of following options"<<endl;
cout<<"1. deposit"<<endl;
cout<<"2. withdraw"<<endl;
cout<<"3. exit"<<endl;
int input;
cin >>input;
if(input>=1 && input<=3 && cin)
{
return input;
break;
}
else
{
cout<<"You have only 3 options. Please chooses 1,2 or 3"<<endl;
}
}
}
It works fine if the input is int number
If input is less then 1 or greater than 3, this function re-ask user to input number btw 1 and 3.
However, if the input is character such as 'f', it does an infinite loop.
This function know that 'f' is wrong input..
I did my own research in the Internet.
!cin and cin.fail() do not work.
Can you help me?
When you try to read an integer but pass something else, the reading fails and the stream becomes invalid. Whatever caused the error remains in the stream. This leads to infinite loop.
To fix that, clear the error flags and ignore the rest of the line in your else clause:
else
{
cout<<"You have only 3 options. Please chooses 1,2 or 3"<<endl;
cin.clear(); // remove error flags
// skip until the end of the line
// #include <limits> for std::numeric_limits
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
You can modify it like this:
int displayMenu()
{
while(true)
{
cout<<"Please choose one of following options"<<endl;
cout<<"1. deposit"<<endl;
cout<<"2. withdraw"<<endl;
cout<<"3. exit"<<endl;
char input = cin.get(); //read a character
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //skip the rest of characters in cin buffer so that even if a user puts "123" only the first one is taken into account
if(input>='1' && input<='3' && cin) //check whether this is '1', '2' or '3'
{
return input;
break;
}
else
{
cout<<"You have only 3 options. Please chooses 1,2 or 3"<<endl;
}
}
}

Clear entire line from cin instead of one character at a time when the user enters bad input

I have a question on some commands for cin. I'm still very new to c++ so bear with me.
I'm doing a simple calculation program where the user inputs a value and the program does a calculation with the input. I'm attempting to create a loop that checks the input to ensure the user inputted and number. After some research I found that using cin.clear and cin.ignore will clear the previous input so the user can input a new value after the loop checks to see if its not a number. It works well, except when the user inputs a word larger then 1 letter. It then loops and removes each letter one at a time until the previous cin is cleared. Is there a way to remove the entire word rather then one character at a time? I feel I have incorrectly interpreted what the cin commands actually do.
Here is the code in question:
//Ask the user to input the base
cout << "Please enter the Base of the triangle" << endl;
cin >> base;
//A loop to ensure the user is entering a numarical value
while(!cin){
//Clear the previous cin input to prevent a looping error
cin.clear();
cin.ignore();
//Display command if input isn't a number
cout << "Not a number. Please enter the Base of the triangle" << endl;
cin >> base;
}
I think you could get the answer in many ways on the net. Still this works for me:
#include <iostream>
#include <limits>
using namespace std;
int main() {
double a;
while (!(cin >> a)) {
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Wrong input, retry!" << endl;
}
cout << a;
}
This example is simpler than the one linked in the comments since you are expecting input from the user, one input per line.

C++ problems involving getline() and a loop

I am working an a school assignment and am beating my head against a wall right now trying to figure out why my program is not behaving as I'd like it to!
int main(){
string input;
char choice;
bool getChoice(char);
string getInput();
CharConverter newInput;
do{
cout << "Please enter a sentence.\n";
getline(cin, input);
cout << newInput.properWords(input) << endl;
cout << newInput.uppercase(input) << endl;
cout << "Would you like to do that again?\n";
cin >> choice;
} while (getChoice(choice) == true);
return 0;
}
This program works fine on the first round, but I am having a problem when getChoice() == true, and the do while block is looped a second time. On the second loop, the program asks for me to enter a sentence again, but then just jumps to "Would you like to do that again?" without allowing user input or outputting the results of the properWords() and uppercase() functions. I suspect that there is something about getline that I do not understand, but I have yet to find it through my googling. Any help out there?
edit: there was a mistake in my original explanation.
This is because reading input with getline does not mix well with reading input character-by-character. When you enter the Y/N character to indicate if you want to proceed or not, you also press Enter. This puts \n in the input buffer, but >> does not take it from there. When you call getline, the \n is right there, so the function returns an empty string right away.
To fix this, make choice a std::string, use getline to read it, and send the first character to getChoice function, like this:
string choice;
...
do {
...
do {
getline(cin, choice);
} while (choice.size() == 0);
} while (getChoice(choice[0]));