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 8 years ago.
Improve this question
When I run this program, my output is just a loop of my cout. it as if the cin is now getting skipped? Does anybody have an idea as to why this is happening?
TryAgain:
cout<<"\nEnter a number greater than 1 and less than 100: "; // 21 - Request a Number
cin>>num; // 22 - Store the number
if (cin.fail()) {
cout << "Please enter a number!\n\n";
goto TryAgain;
}
if (num<=1){ // 24 - IF NUMBER IS BELOW 1
cout<<"Oh no, " << num << " is too small!\n\n"; // 25 - Print Error Message
return 0;
}
if (num>=100){ // 29 - IF NUMBER IS OVER 100
cout<<"Oh no, " << num << " is too large!\n\n"; // 30 - Print Error Message
return 0;
}
else if (isprime(num)){ //Call isprime // 34 - IF ISPRIME IS TRUE
cout << "True, " << num << " is a prime number!!\n\n"; // 35 - Print True Message
}
else{ // 38 - IF ISPRIME OS FALSE
cout << "False, " << num << " is not a prime number!!\n\n"; // 39 - rint False Message
}
When cin fails, it is put into an error state that will cause it to always fail. You need to clear that error state.
cin.clear();
If you're going to do the same input operation again, you also need to remove (at least some of) the previously entered data, or else cin will fail again.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
You have to use two member functions of std::cin: ignore and clear. For example
#include <limits>
//...
if (cin.fail()) {
cout << "Please enter a number!\n\n";
cin.clear();
cin.ignore( numeric_limits<streamsize>::max() );
goto TryAgain;
}
Also it is a bad idea to use goto statement. You could write
do
{
if ( !cin )
{
cin.clear();
cin.ignore( numeric_limits<streamsize>::max() );
}
cout<<"\nEnter a number greater than 1 and less than 100: ";
cin>>num;
} while ( !cin );
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 months ago.
Improve this question
The folowing code tells user to input their age, it is set to be input interger between 0 and 120, it is capable to deal with wrong input like 'M' or 133 or -1. Warning message goes like this:Warning message
case 1: // input age
cout << "Enter your age: ";
cin >> age;
if(age <= 0 || age > 120){ // if the input type or number was wrong, it goes here
while(1){
cout << "Invalid input! Please enter again" << endl << ">>>";
age = -1;
cin >> age;
if(age > 0 && age <= 120) {break;}
}
}
However, it'll go wrong if I input something like \ or [.
Repeating Warning message
How can I solve this?
By emptying the keyboard buffer before a new entry.
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int age;
cout << "Enter your age: ";
cin >> age;
while(age <= 0 || age > 120)
{
cout << "Invalid input! Please enter again" << endl << ">>>";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin >> age;
}
return 0;
}
lets walk through this.
You type in something wrong and enter the if clause.
In here you enter the while loop and ask the user again for a input. This input is instantly answered because there is still something in the input stream.
Therefore you need to flush the cin stream before asking again for an input (You can place the flush in for example line 4).
You should be able to clear the stream with a command like this:
How do I flush the cin buffer?
Unfortunately I'm not able to test that out by myself but you can give it a try and I hope it helps!
This question already has answers here:
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed last year.
int num = 0;
while(true){
cout << "enter num: ";
cin >> num;
if(!(num)){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "num must be an int" << endl;
}else if(num <= 0){
cout << "num must be greater than 0" << endl;
}else if(static_cast<double>(static_cast<int>(num)) != num){
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "num must be an int" << endl;
}else{
break;
};
};
I've been looking through SO and I found some threads that addressed similar issues, but nothing that is specific to what I'm trying to achieve. I'm only trying to accept integer inputs, no decimals, no strings, no characters. If I enter in a negative number or 0, it'll throw me an error saying "num must be greater than 0." If I enter in a, it'll throw me an error saying "num must be an int." If I enter 1.0, it'll throw me an error saying "num must be an int."
The problems I'm running into with this is when I enter in 0 for example, instead of executing the conditional statement that checks (num <= 0), it runs the conditional statement that says (!(num)). The other problem I'm running into is when I enter in a value that has a decimal, like 2.0, it'll truncate the numbers after the decimal and send in 2 as the value, completely glossing over the check to see if it's a decimal value and telling the program that it's a valid integer when it's not.
Does anyone have a solution for this, or an article link that solves problem like mines? Thank you!
This:
cin >> num;
if(!(num))
Should be this:
if (!(cin >> num))
You are checking the value of num when you should instead be checking the error state of cin. operator>> returns a reference to the input stream, which is then implicitly convertible to bool, where false means the stream encountered an error.
Also, this is completely useless:
else if(static_cast<double>(static_cast<int>(num)) != num)
Casting an int value to an int is a no-op, and casting an int value to a double back to an int will get you the original int value.
num is an int, it can't read in anything else. So, by the time your code reaches this point, you know num must be holding a valid int value. However, if the user had actually entered a floating-point number instead, operator>> would have stopped reading at the decimal point, leaving it and the remaining fractional value in cin's input buffer for later reading.
Also, the 2nd call to cin.ignore() is wrong. By that point, operator>> was able to read in an int value, it just wasn't satisfactory to you. So don't ignore subsequent input yet.
If you really need to differentiate between integer and floating-point input, you will have to read in the input as a string first, and then parse it to see what it actually holds, eg:
int num = 0;
string s;
size_t pos;
while (true){
cout << "enter num: ";
if (!(cin >> s)){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "input error, try again" << endl;
}
else{
try{
num = stoi(s, &pos);
if (pos != s.size()) throw invalid_argument("");
if (num > 0){
break;
}
cout << "num must be greater than 0" << endl;
}
catch (const exception &){
cout << "num must be an int" << endl;
}
}
}
Online Demo
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm new to C++ and I want to be able to run the program again as long as the user desires. But the problem is, whenever I loop the program, it doesn't show the outputs anymore. How do I fix this problem?
long numCoco = 0, numPeople = 0;
char again = 'Y';
do
{
cout << "enter the number of coconuts gathered: ";
cin >> numCoco;
//validate user input
while (numCoco < 1 || numCoco > 5000)
{
if (cin.fail())
{
cin.clear();
cin.ignore();
cout << "You have entered the wrong input\n";
cin >> numCoco;
}
if (!cin.fail())
break;
}
for (numPeople = numCoco - 1; numPeople > 1 && !found; numPeople--)
{
found = splitCoco(numCoco, numPeople);
if (found)
{
cout << numCoco << " Coconuts, " << numPeople << " Persons, " << " and 1 monkey\n\n";
}
}
if (!found)
{
cout << numCoco << " no solution\n\n";
}
cout << "Run again? (Y/N): ";
cin >> again;
} while (again == 'y' || again == 'Y');
Desired Output
Enter the number of coconuts gathered: 25
25 coconuts, 3 persons, and 1 monkey
Run again(Y/N): y
Enter the number of coconuts gathered: 30
30 coconuts, No solution
Run again(Y/N): N
Actual Output
Enter the number of coconuts gathered: 25
25 coconuts, 3 persons, and 1 monkey
Run again(Y/N): y
Enter the number of coconuts gathered: 30
Run again(Y/N): N
You must set "found" variable to 0 before the for loop.You expect "found" variable to be 0 when the input is 30 but actually the line:
found = splitCoco(numCoco, numPeople);
never executes in the second iteration.
The problem here is that after the first iteration(when input is 25), found is set to true and in the second iteration(when input is 30), found is still true so both the condition of "for loop" and the condition of the "if block" are false so none of them executes; so nothing is printed and the loop starts over.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am creating a game for two people to play to guess a number, I had it working with an if statement, but if player 2 gets it wrong I would like them to be able to guess again until they get it right. I decided to use a while loop, but I am getting an infinite loop of text, what can I do to stop it?
Here is my code: (I have commented out the if statement while working on the while loop)
#include <iostream>
using namespace std;
int main() {
int player1; //Number variable 1
int player2; //Number variable 2
cout << "Player 1 type in a number between 1 and 100: "; //Asks player to enter a number
cin >> player1;
system("CLS");
cout << "Player 2 guess the number between 1 and 100: "; //Asks guess a number
cin >> player2;
while(player2 != player1)
{
cout << "Player 2 guess the number between 1 and 100: ";
}
system("pause");
system("pause"); //Keeps window on screen
return 0;
}
Also any feedback on how to make my code better would be highly appreciated.
You got two things wrong
The braces for the while loop.
You are not reading user input again in the loop.
Modify the loop as below..
while(player2 != player1)
{
cout << "Player 2 guess the number between 1 and 100: ";
cin >> player2;
}
The problem is that within the while loop you never change the value of player1 or player2. Hence if they are unequal the first time they will be forever unequal and the code will loop infinitely. To fix this you need to move the code which changes the values into the body of the loop. Hence the user has a chance to change the values.
do {
cout << "Player 2 guess the number between 1 and 100: "; //Asks guess a number
cin >> player2;
if (player2 == player1)
cout << "Correct!" << endl;
else
cout << "Wrong, try again" << endl;
} while(player2 != player1)
If you don't use an open brace after the while statement it only refers to the following expression.
Additionally, after the while you are not reading data from the user again, so how do you expect player2 to ever change?
In terms of code organisation it would be better to set player2 to something obviously invalid, like -1, and have the while at the beginning, without the previous read and if statement so it doesn't have to be special cased.
Try this...
do
{
cout << "Player 2 guess the number between 1 and 100: "; //Asks guess a number
cin >> player2;
} while (player2 != player1)
Your curly brackets are in the wrong position and you never read input from the player after the first time.
if you change it like this, the second player will be asked again.
....
while(player1 != player2){
cout << "Player 2 guess the number between 1 and 100: ";
cin >> player2;
}
In addition, you should add some basic error handling, for example checking if the cin.error() flag is set.
Your while has no brackets, which makes the line right after it repeat forever!
Put the cout and cin for player 2 guess inside a do-while loop and then verify the condition.
cout << "Player 1 type in a number between 1 and 100: "; //Asks player to enter a number
cin >> player1;
system("CLS");
do {
cout << "Player 2 guess the number between 1 and 100: ";
cin >> player2;
} while(player2 != player1);
In
while(player2 != player1)
{
cout << "Player 2 guess the number between 1 and 100: ";
}
Nothing in the loop ever changes player2 nor player1, so if the condition player2 != player1 was true, it will remain true.
The loop
while(player2 != player1)
{
cout << "Player 2 guess the number between 1 and 100: ";
}
is an endless loop, because the variables player2 and player1 are not changed inside of the loop. If the while condition is true when entering the loop, it will stay true forever.
UPDATE:
To allow player2 to guess repeatedly, and hence change the number that he guessed and get out of the while loop, add cin >> player2; after the cout statement:
while(player2 != player1)
{
cout << "Player 2 guess the number between 1 and 100: ";
cin >> player2;
}
So, this program I am working on is not handling incorrect user input the way I want it to. The user should only be able to enter a 3-digit number for use later in a HotelRoom object constructor. Unfortunately, my instructor doesn't allow the use of string objects in his class (otherwise, I wouldn't have any problems, I think). Also, I am passing the roomNumBuffer to the constructor to create a const char pointer. I am currently using the iostream, iomanip, string.h, and limits preprocessor directives. The problem occurs after trying to enter too many chars for the roomNumBuffer. The following screenshot shows what happens:
The relevant code for this problem follows:
cout << endl << "Please enter the 3-digit room number: ";
do { //loop to check user input
badInput = false;
cin.width(4);
cin >> roomNumBuffer;
for(int x = 0; x < 3; x++) {
if(!isdigit(roomNumBuffer[x])) { //check all chars entered are digits
badInput = true;
}
}
if(badInput) {
cout << endl << "You did not enter a valid room number. Please try again: ";
}
cin.get(); //Trying to dum- any extra chars the user might enter
} while(badInput);
for(;;) { //Infinite loop broken when correct input obtained
cin.get(); //Same as above
cout << "Please enter the room capacity: ";
if(cin >> roomCap) {
break;
} else {
cout << "Please enter a valid integer" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
for(;;) { //Infinite loop broken when correct input obtained
cout << "Please enter the nightly room rate: ";
if(cin >> roomRt) {
break;
} else {
cout << "Please enter a valid rate" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
Any ideas would be greatly appreciated. Thanks in advance.
Read an integer and test whether it's in the desired range:
int n;
if (!(std::cin >> n && n >= 100 && n < 1000))
{
/* input error! */
}
Although Kerrek SB provide an approach how to address the problem, just to explain what when wrong with your approach: the integer array could successfully be read. The stream was in good state but you didn't reach a space. That is, to use your approach, you'd need to also test that the character following the last digit, i.e., the next character in the stream, is a whitespace of some sort:
if (std::isspace(std::cin.peek())) {
// deal with funny input
}
It seems the error recovery for the first value isn't quite right, though. You probably also want to ignore() all characters until the end of the line.