cin in c++ do while loop [duplicate] - c++

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 8 years ago.
I have a c++ program.I am using a do while loop to re execute the program after every cycle if the user chooses to run it again.The program runs fine on the first loop but on the subsequent runs the program skips requesting for a diver's name.It just prints the prompt for diver's name and number of judges together as shown below.How can i correct that?
On first run,notice the user is prompted to enter the number of judges after entering the diver's name as below
On the subsequent runs,the program does not wait for user to input the diver's name before requesting for the number of judges,it prints the two prompts together and only number of judges can be input as shown below
And here is the main class which holds the logic of execution:
int main()
{
char rerun;
do{
srand(time(NULL));
int number_of_judges=0;
char option,dive;
char dives[3];
string divenames[3];
double** scores;
string diverName="";
cout<<"What is the diver's name? "<<endl;
getline(cin,diverName);
number_of_judges=getjudges();
cout<<number_of_judges;
displayMenu();
for(int i=0;i<3;i++){
cout<<"Enter dive "<<i+1<<" to be judged(A-E)";
cin>>dive;
dive=tolower(dive);
while(!(dive=='a' || dive=='b' || dive=='c' || dive=='d' || dive=='e' ) ){
cout<<"You entered the wrong choice.Choice must be from (a-e)."<<endl;
cout<<"Enter dive "<<i+1<<" to be judged(A-E)";
cin>>dive;
dive=tolower(dive);
}
dive=tolower(dive);
dives[i]=dive;
}
for(int i=0;i<3;i++){
divenames[i]=getDive(dives[i]);
}
scores=getRandom();
getScores(diverName,scores,divenames);
cout<<"Do you want another try?";
cin>>rerun;
while(rerun !='y' && rerun!='n'){
cout<<"You have entered an invalid option.\nPlease try again.";
cin>>rerun;
rerun=tolower(rerun);
}
}
while(rerun=='y' || rerun == 'Y');
std::getchar();
return 0;
}
Any help will be greatly appreciated.

In the line:
cin>>rerun;
a charachter is extracted from the stream. This operation, however, leaves a newline in the buffer. So, when in the next step, you do:
getline(cin,diverName);
you are trying to read all the input up to newline and in the buffer there is already a newline (coming from the previous step): then this operation ends immediately.
The solution is to add an instruction after cin>>rerun of this type:
cin.ignore();
in this manner the newline left in the buffer will be discarded in the next operation.

Related

Checking if input is an integer, and inputting more than 1 character results in multiple statements being printed in console instead of just once [duplicate]

This question already has answers here:
cin input (input is an int) when I input a letter, instead of printing back incorrect once, it prints correct once then inc for the rest of the loop
(2 answers)
Closed 2 years ago.
{
valid = true; //Assume the cin will be an integer.
cin >> menuValue;
if (cin.fail()) //cin.fail() checks to see if the value in the cin
//stream is the correct type, if not it returns true,
//false otherwise.
{
cin.clear(); //This corrects the stream.
cin.ignore(); //This skips the left over stream data.
cout << "Please enter an Integer from 1-6 only." << endl;
valid = false; //The cin was not an integer so try again.
}
}
Im trying to make an error checkpoint, where is a user inputs something that isn't an integer, it'll ask them to rein put the number, the only issue is If I were to input something such as jiasdhais, it would print the same message as many times as the length of the input. Any way around this?
Try this:
{
int input;
if( !( std::cin >> input) ){
//in case of fail do stuff
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} else {
//then check for 1-6
//your code ...
}
}
If input is not integer it will be discarded.More specifically if your architecture holds int as 4bytes then the input should be in range -2,147,483,648 to 2,147,483,647, otherwise will be discarded.

Running as infinite loop [duplicate]

This question already has an answer here:
C++ Beginner Infinite Loop When Input Wrong Data Type and Help Evaluate My Code
(1 answer)
Closed 3 years ago.
When I try to call this function and provide a value to variable grade other than integer, the do-while loop kept on executing and don't even prompt for an input to the variable of type char. Kindly help me to figure out why loop kept on executing.
//User Input function
int userInput(){
int grade,question;
char choice='y';
srand(time(0));
do{
//displayMenu();
cout<<endl;
cout<<"Please select grades, use number 1 to 5: ";
cin>>grade;
/*if(grade<1 || grade>5){
cout<<"You have entered an invalid grade!"<<endl;
}
else{
cout<<"Enter number of questions you want to generate: ";
cin>>question;
while(question<1){
cout<<endl;
cout<<"You have entered an invalid number"<<endl;;
cout<<"Enter number of questions you want to generate: ";
cin>>question;
}
cout<<endl;
questionGenerator(grade,question);
cout<<endl;
cout<<"Press n/N to Quit or Press any key and then Enter";
cin>>choice;
system("cls");
}*/
cout<<"Type N/n to Quit or Press Any Key and then Enter"<<endl;
cout<<"Your choice? : ";
cin>>choice;
system("cls");
}while(choice!='n' && choice!='N');
return 0;
}
Well your grade variable is an intteger, so it cant take any other type of variable. If you are going to input a char then why is grade an integer or if you are going to inout a string? If you need this to be possible then maybe try using arrays and start turning them from arrays to: integers floats booleans strings or characters. Also be careful because a char value can be assigned to a number (character code).

C++ store string sentences from user input into a vector

I am a beginner at C++ and currently learning vectors. Here is a simple code where program gets the user input and stores it in a vector then proceed to print the stored values from each element:
int main(){
vector<string> myVector;
string myInput;
int n;
cin>>n;
cin.ignore(numeric_limits<streamsize>::max(),'\n');
for(int i = 1; i <= n;i++){
cout<<"loop count: "<<i<<endl; //added for checking the current loop
getline(cin, myInput);
cin.ignore(numeric_limits<streamsize>::max(),'\n');
myVector.push_back(myInput);
}
for(unsigned int j = 0;j < myVector.size(); j++){
cout<<myVector[j]<<endl;
}
return 0;
}
but when I run my code, during the user string input, it lets me enter two strings before finally going to the next loop. the program only prints out the first entered string for each loop though. So my questions are:
1) What is the reason behind this? Why does user need to enter two strings before going to next loop? Can someone explain to me.
2) how can this be fixed?
EDIT: Here are my sample inputs and the output:
input:
3
input loop count: 1
we are
the champions
input loop count: 2
no time
for losers
input loop count: 3
we are
the champions
output:
we are
no time
we are
The problem is the ignore call inside the loop.
The std::getline will silently eat up the trailing newline, but since you then call ignore you must enter a second line for ignore to be satisfied.
Simply remove the ignore call from the loop and it should work as you expect.
Did you try to put cin.clear(); cin.sync(); before getline function? cin and getline give you problems when you use them at the same time.

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;
}
}
}

Infinite loop after receiving input and testing to see if it's an int in C++ [duplicate]

This question already has answers here:
Infinite loop with cin when typing string while a number is expected
(4 answers)
Closed 6 years ago.
I'm trying to take an integer from the user. I'm using cin.ignore to make sure that the input is an int. However, when it is not an int, it causes the program to enter an infinite loop.
int steps = 0;
while (steps<2 || steps>100)
{
char tmp[1000];
cout << "Zadejte pocet cyklu: ";
cin >> steps;
cin.ignore(numeric_limits<int>::max(), '\n');
if (!cin || cin.gcount() != 1)
{
cin.getline(tmp,1000);
steps = 0;
}
}
If the input stream doesn't contain an integer when you do cin >>
steps, the stream enters an error state, which must be explicitly
cleared (cin.clear()). Until then, the error state remains, and all
further attempts to input will be treated as no-ops.