I'm trying to make a validation loop in C++ that checks the user's input until they enter a number between 0 and 100 and however my loop only checks the first condition. Any guidance is appreciated!
#include <iostream>
using namespace std;
int main()
{
const int max_num = 100;
const int min_num = 0;
int num;
cout << "Enter a number between 0 and 100" << endl;
cin >> num;
do {
if (!(cin >> num))
{
cout << "ERROR:The value provided was not a number" << endl;
cin.clear();
cin.ignore(1024, '\n');
cout << "Enter a number between 0 and 100" << endl;
cin >> num;
}
else if (num<min_num || num>max_num)
{
cout << "ERROR: value out of range" << endl;
cin.clear();
cin.ignore(1024, '\n');
cout << "Enter a number between 0 and 100" << endl;
cin >> num;
}
} while (!(cin >> num) || (num<min_num || num>max_num));
return 0;
}
Add lots of logging to your code so that you know what it's doing. This will help you find the problem. For example, instead of:
cout << "Enter a number between 0 and 100" << endl;
cin >> num;
Try:
cout << "Enter a number between 0 and 100" << endl;
cerr << "About to read into num outside the loop" << endl;
cin >> num;
cerr << "Read into num outside the loop, got: " << num << endl;
And so on, throughout your code. This should give you enough information to find the bug. Alternatively, use a debugger with a single step function to accomplish the same thing.
Check that in the part of while:
instead of
while (!(cin >> num) || (num<min_num || num>max_num));
this:
while (!cin || (num<min_num || num>max_num));
the same for the upper if
cin >> num means putting user input to the variable num . So you are trying to take user inputs 2 times in the loop. Maybe the check condition: (num == (int)num)will solve your problem. It will try to verify the number you have stored in num is really of the type int
Related
i am trying to find the average but this could not resolve. This code showing me 'runtime erorr' kindly help me my code is here:
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! number should in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
I do not understand what is 'n' standing for. I found some problems with your script. First of all u should define the 'n'. Secondly, it's better not to use the loop for checking.
Thirdly, i suggest u to use this code":
int n;
cin>>n;
if(n>100 && n<0)
{
cout << "Error! number should in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
I'm designing a number guessing algorithm for use as a game.
Can anyone suggest why does the algorithm end after the first condition?
#include <iostream>
using namespace std;
int main()
{
int num = 5;
int guess;
cout << "Guess a number \n";
cin >> guess;
if (guess==num)
{
cout << "You guessed the correct number \n";
}
else if (guess < num)
{
cout << "Your guess is lower than the number \n";
cout << "Guess again \n";
cin >> guess;
}
else
{
cout << "Your guess is higher than the number \n";
cout << "Guess again \n";
cin >> guess;
}
return 0;
}
You need some kind of loop if you want that the algorithm would be repeated.
For example
#include <iostream>
using namespace std;
int main()
{
int num = 5;
int guess;
cout << "Guess a number \n";
do
{
cin >> guess;
if ( guess == num )
{
cout << "You guessed the correct number \n";
}
else if ( guess < num )
{
cout << "Your guess is lower than the number \n";
cout << "Guess again \n";
}
else
{
cout << "Your guess is higher than the number \n";
cout << "Guess again \n";
}
} while ( guess != num );
return 0;
}
If you wish to guess again I'd recommend a loop. Otherwise your code works as intended.
while(number != guess)
{
if(number * 2 < guess){
cout << "Way to high. Try again." << endl;
cin >> guess;
}
if(number / 2 > guess)
{
cout << "Tip : My number is NOT low. Try again." << endl;
cin >> guess;
}
if(number < guess)
{
cout << "To high try something lower. Feed me a number." << endl;
cin >> guess;
}
if(number > guess)
cout << "To low, try again." << endl;
cin >> guess;
}
I am trying to verify the user input, but I have tried two compilers and I either have one of two things happen. Either it will:
-Constantly loop the error message without asking for user input
OR
-Wait for user input, and if the input is incorrect, will constantly loop the error message.
Here is the code:
cout << "Input number of the equation you want to use (1,2,3): " ;
cin >> userInput;
cout << endl;
while (userInput <= 0 || userInput >= 4)
{
cout << "Please enter a correct input (1,2,3): " ;
cin >> userInput;
cout << endl;
}
if (userInput == 1)
{
userInput is declared as an integer. Is there an easier way to verify user input, or a while loop is necessary? I am still very new to coding.
While using int userInput seems straight forward, it fails when the user inputs non-numeric values. You can use a std::string instead and check, if it contains a numeric value
std::string userInput;
int value;
std::cout << "Input number of the equation you want to use (1,2,3): " ;
while (std::cin >> userInput) {
std::istringstream s(userInput);
s >> value;
if (value >= 1 && value <= 3)
break;
std::cout << "Please enter a correct input (1,2,3): " ;
}
std::istringstream is similar to other input streams. It provides input from an internal memory buffer, in this case the value provided by userInput.
I would add an additional check to make sure that if the user enters non-integral input, the stream is cleared before attempting the next read.
cout << "Input number of the equation you want to use (1,2,3): " ;
cin >> userInput;
cout << endl;
while (userInput <= 0 || userInput >= 4)
{
if ( !cin.good() )
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
cout << "Please enter a correct input (1,2,3): " ;
cin >> userInput;
cout << endl;
}
I would suggest using a do loop instead so you have less repeated lines
int userInput = 0;
do
{
cout << "Input number of the equation you want to use (1,2,3): " ;
cin >> userInput;
cout << endl;
if ( !cin.good() )
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
} while (userInput <= 0 || userInput >= 4);
You don't want to cin >> int, if you are to perform any error checking. If the user enters a non-integer, you'll end up in difficult-to-recover-from situations.
Rather, cin into a string, perform any error checking you want and convert the string to a integer:
long x;
string sx;
cin >> sx;
x = strtol(sx.c_str(), NULL, 10);
I'm trying to write a program which calculates prime numbers and I have issues with a do-while-loop I am using.
Code:
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
unsigned long int lower_limit;
unsigned long int upper_limit;
cout << "\n" << "Program calculates prime numbers in a given range between 2 and 4.294.967.295.";
cout << "\n" << "Input range in which prime numbers are to be calculated... ";
do
{
cout << "\n\n" << "Lower Limit:\t"; cin >> lower_limit;
cout << "\n" << "Upper Limit:\t"; cin >> upper_limit;
if(lower_limit >= upper_limit)
{
cout << "\nInvalid Input: Value of Upper Limit has to be bigger than value of Lower Limit.";
cout << "\nSelect new numbers.";
}
if(!(cin >> lower_limit) || !(cin >> upper_limit))
{
cout << "\nInvalid Input: Values of Lower Limit and Upper Limit have to be integers.";
cout << "\nSelect new numbers.";
}
}while(lower_limit >= upper_limit || !(cin >> lower_limit) || !(cin >> upper_limit));
return(0);
}
If I input values to trigger Lower Limit >= Upper Limit it triggers the first error properly, but doesn't repeat the do-while-loop afterwards and doesn't close the program (return(0)) either... So the program is not repeating the do-while-loop, neither is the program exiting it. I really have no clue what it is actually doing there.
If I input values to trigger !(cin >> lower_limit) || !(cin >> upper_limit) ("adfd" or the like) the whole program just goes mental and rapidly repeats the do-while-loop, even ignoring the cin >> lower_limit; and cin >> upper_limit; statements.
Does anybody have an idea that can help me out?
Cheers!
One point is that if you get invalid input, you need to clear the error state by:
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Your loop should be changed to something like:
do
{
while ( !(cin >> lower_limit >> upper_limit) ) {
cout << "Invalid input, Please re-enter\n";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
if(lower_limit >= upper_limit)
{
cout << "\nInvalid Input: Value of Upper Limit has to be bigger than value of Lower Limit.";
cout << "\nSelect new numbers.";
}
} while(lower_limit >= upper_limit);
This program should check if entered number is integer. It works fine with strings but not with doubles.
int test;
cout << "Enter the number:" << endl;
while(true) {
cin >> test;
if (!cin || test < 0) {
cout << "Wrong input, enter the number again:" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
test is int. istream >> operator is just dynamic casting to int and, then, you're losing decimal part.
Yo can just define test as float and cast it to int when needed.
Edit: Answering you last edit (I didn't refresh so I missed this part), what is happening is that, without the gotoyou're looping twice:
You enter 1.5
test is 1 and you don't enter if, so cin is not cleaned up.
loops again and cin immediately returns.
test is 0 so enters if statement and complains.
Hope this helps
Try this:
int test;
cout << "Enter the number:" << endl;
while ( true )
{
cin >> test;
if (!(test < 0 || !cin))
break;
}
cout << "Your chosen number is: " << test << endl;
Is that what you want?