How to set a range of int value in C++ - c++

If I have an int a; and I want to set a value for this int (cin >> a;) in a range 1 < a < 1000, what is the most effective way how to type it via code? Is there a better way then if(a <=1 || a >= 1000)? Since if I would have multiple of int which I wanted to be limited by their value, I don't want to type a condition for every single one.

Checking the condition a <=1 || a >= 1000 is exactly what you'd do 👍
You will want to use a loop here, though, to re-ask for input if the input is not in the correct range.

Using the if is the best way to do what you are asking for. But, if you need to handle multiple ints, you should wrap the if inside of its own function that you can call whenever needed, eg:
int askForInt(int minValue, int maxValue)
{
int value;
do {
cout << "Enter an integer (" << minValue << "-" << maxValue << "): ";
if (cin >> value) {
if (value >= minValue && value <= maxValue) break;
cout << "Value out of range! Try again." << endl;
}
else {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Bad input! Try again." << endl;
}
}
while (true);
return value;
}
...
a = askForInt(1, 1000);

Related

Validating input with do while loop

I am trying to minimize hardcoding numbers into my program and allowing for users to define max and min parameters along with making sure that the input is valid.
#include <iostream>
int main(){
int max, A=0;
do
{
std::cout << "What is the max?\n";
std::cin >> max;
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore();
std::cout << "not an integer, try again\n";
continue;
}
if(max < -1000){
std::cout << "That doesnt make much sense, please enter the max again.\n";
}
} while (max <A); \\HERE IS WHERE THE PROBLEM IS.
std::cout << "The max number of steps are " << max <<std::endl;
return 0;
}
If A is 0 or less, the program doesn't ask for user input again. instead the program just exits the loop.
If A is 1 or more, then then the program loops until a valid input is provided.
I would like the max number to be any int number, including negatives. This is working for positive numbers, but not for maximums that are 0 or less.
do
{
//ask for input
//input taken
} while (A>=1);
This will the code you have to use for the scenario described at the last line. One more point you just forget to assign any value to A according to your logic.
Thanks!
If A is 1 or more, then then the program loops until a valid input is provided. - You are saying exactly what the while loop needs to do. Just implement it.
} while (A >= 1); \\If A is greater than or equal to 1 then loop until valid.
std::cout << "The max number of steps are " << max <<std::endl;
return 0;
}
To answer your follow up question:
} while (A >= 1 && max <= 0); \\If A is greater than or equal to 1 then loop until valid.
std::cout << "The max number of steps are " << max <<std::endl;
return 0;
}
I would suggest writing a custom function that takes an acceptable range of min/max values as input parameters, eg:
int promptForInt(const string &prompt, int minAllowed, int maxAllowed)
{
int value;
std::cout << prompt << "\n";
do
{
if (!(std::cin >> value)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "not an integer, try again\n";
continue;
}
if ((value >= minAllowed) && (value <= maxAllowed)){
break;
}
std::cout << "not an allowed integer, enter a value between " << minAllowed << " and " << maxAllowed << ".\n";
}
while (true);
return value;
}
int main(){
int max = promptForInt("What is the max?", -1000, 1000);
std::cout << "The max number of steps are " << max << std::endl;
return 0;
}

How do I determine the highest and lowest value using do while loops

I am currently stuck in my homework and the problem is that I need to create a program that will ask for 5 integer numbers from which I should determine the highest and lowest value. I am quite confused as of now, and my initial code is this:
#include<iostream>
using namespace std;
int main(){
int num1,num2,num3,num4,num5,min=0,max=0;
cout << " Enter 1st number : ";
cin >> num1;
cout << " Enter 2nd number : ";
cin >> num2;
cout << " Enter 3rd number : ";
cin >> num3;
cout << " Enter 4th number : ";
cin >> num4;
cout << " Enter 5th number : ";
cin >> num5;
do{
if(num1<num2 && num1<num3 && num1<num4 && num1<num5 ){
max = num1;}
if(num2<num1 && num2<num3 && num2<num4 && num2<num5 ){
max = num2;}
if(num3<num1 && num3<num2 && num3<num4 && num3<num5 ){
max = num3;}
if(num4<num1 && num4<num3 && num4<num2 && num4<num5 ){
max = num4;}
if(num5<num1 && num5<num3 && num5<num4 && num5<num2 ){
max = num2;}
}while(max>0);
cout << " The highest number is : " <<max;
return 0;
}
Any help would be appreciated. Thanks in advance!
You should store your numbers into a std::vector<int> or std::array and then use the std::minmax_element algorithm to obtain the largest and smallest number.
If you are allowed to use std::max and std::min, you can use:
max = std::max({num1, num2, num3, num4, num5});
min = std::min({num1, num2, num3, num4, num5});
to simplify the code in the loop.
This would be my solution without using arrays.
I'd suggest you to try it yourself before. You don't learn when you just copy code.
#include <iostream>
int main() {
int i=0, num, min=INT_MAX, max=INT_MIN;
do {
std::cout << "Enter number: ";
std::cin >> num;
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
i++;
} while (i < 5);
std::cout << "The max number is: " << max << std::endl;
std::cout << "The min number is: " << min << std::endl;
return 0;
}
If you don't need to remember, you can loop for e.g. 5 times, then have a comparison before asking the next number.
so generally (idea, write it yourself and learn):
for (5 times)
ask user input, save as input
if largest number is null, then equal to input
else if largest number is smaller, then set input equal to largest number
Continue for loop times.
Rather than compare all the numbers each time. Simply compare your current smallest against the numbers in sequence.
int data[5];
// read numbers into data.
int min = data[0]; // Guess that number 0 is the smallst number.
// Now check if the guess is correct and update if you are wrong.
for(int loop = 0; loop < 5; ++loop)
{
// check if data[loop] is smaller than your current guess.
// if it is smaller than update your guess.
// when you have checked all the values exit the loop.
}
std::cout << "Smallest: " << min << "\n";
There is no need to use a loop to do this you can do that without it else if it's necessary to use a loop you must use an array or some other data structure

IF or WHILE for numerical input checker

I've been working on a program that calculates the mean of the user's inputs. I couldn't figure out yet, what to use for the input checker. I can't use arrays or strings yet. How do I check that both inputs are numerical values? And if they are not; how do I ask again for the correct input?
#include <iostream>
using namespace std;
int main()
{
// Get number from user
int input = 0;
double accumulator = 0;
double mean;
cout << "How many numbers would you like me to average together?\n";
cin >> input;
if (input >= 0){ //to check if input is a numerical value
// Compute and print the mean of the user input
int number = 1;
double x;
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
if (x < 0 || x > 0){ //to check if x is a numerical value
accumulator = accumulator + x;
}
else {
cout << "Input incorrect"<< endl;
}
number = number + 1;
}
mean = accumulator / input; // formula corrected
cout << "The mean of all the input values is: " << mean << endl;
cout << "The amount of numbers for the average calculation is: " << input << endl;
}
else {
cout << "Input incorrect"<< endl;
}
return 0;
}
You can use cin.fail to check for errors. Note that if user inputs a number followed by letters, lets say 123abc, then x will be stored as 123 but abc remains in the input buffer. You may wish to clear that right away so abc doesn't appear in the next loop.
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
bool error = cin.fail();
cin.clear();
cin.ignore(0xFFFF, '\n');
if (error)
{
cout << "Input incorrect" << endl;
continue;
}
accumulator = accumulator + x;
number = number + 1;
}
Alternatively you can initialize x. For example
double x = numeric_limits<double>::min();
cin >> x;
cin.clear();
cin.ignore(0xFFFF, '\n');
if (x == numeric_limits<double>::min())
{
cout << "Input incorrect" << endl;
continue;
}
If error occurs then x remains unchanged and you know there was an error, because it is unlikely that the user inputs a number matching numeric_limits<double>::min()
Not related to this issue, but you should also account for divide by zero error.
if (input == 0)
mean = 0;//avoid divide by zero, print special error message
else
mean = accumulator / input;

C++: Asking the user to enter a new number if the number they entered is wrong

I'm trying to get the program to loop again, up to three times, if the user entered a number that does not follow the function defined in the if statement. The code as is, only loops once and then exits. Did I type the for loop incorrectly or is it the if...else statement that is wrong?
#include <iostream>
using std::cout; using std::cin; using std::endl;
int main() {
cout << "Enter a positive odd number less than 40: ";
int num = 0;
for (int a = 0; a < 3; ++a);
cin >> num;
{
if (num < 40 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl;
}
else cout << "That is incorrect, try again!" << endl;
}
}
Did I type the for loop incorrectly or is it the if...else statement that is wrong?
Both. You should (1) remove the semicolon following the for statment; (2) move cin >> num into the for loop body; (3) add break; inside the if.
for (int a = 0; a < 3; ++a)
{
cin >> num;
if (num < 40 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl;
break;
}
else cout << "That is incorrect, try again!" << endl;
}
BTW1: Try to use the debugger, then you'll find out what happened in fact.
BTW2: The code will fail when cin >> num fails (e.g. user entered an invalid value), you might need to check the result of cin >> num, to process the case. Such as:
for (int a = 0; a < 3; ++a)
{
if (cin >> num)
{
if (num < 40 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl;
break;
}
else cout << "That is incorrect, try again!" << endl;
}
else
{
cin.clear(); // unset failbit
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input
cout << "Wrong input, try again!" << endl;
}
}
bool isValid = false;
int num;
while(!isValid)
{
cout << "enter a positive odd integer " << endl;
cin >> num;
if(num < 40 && num > 0 && num % 2 == 1 )
{
cout << "thank you"<<endl;
isValid = true;
}
else
isValid = false;
}
Why not use some thing like this, it will loop until isValid = true which will only happen when your conditions are met?
I understand I guess, if you're doing a school project or some thing and you're forced to do it with a for loop but in general this would be a much better solution for some thing like this than a for loop!

C++ try catch throw

I have a simple recursive factorial program. The main point of this exercise is to handle exceptions. We've been imposed with the limitations of having no negative numbers and no number larger than 12.
{
int factorial(int);
int number = 0;
string s;
while(number != -1)
{
cout << "Please enter a number 1 - 12 " <<endl;
cout << "or -1 to quit the program: ";
try{
cin >> number;
if (number < 0 || number > 12)
throw number;
else
cout << number << " factorial is: " << factorial(number)<<"\n" << endl;
}catch(int number)
{
cout<< "Your number violates the rules; " <<number<<" is either negative or greater than 12.\n"<<endl;
}
}
}
int factorial(int number) {
int temp;
if(number <=1)
return 1;
temp = number * factorial(number - 1);
return temp;
}
My error handling seems like it's working fine, and it's a new concept to me. However, I'd like to do a better job of handling errors. For example, when I type in anything that's not a number, like say a "p" the program starts an infinite loop. How could I code to check and make sure that it's indeed a number a user is putting in?
Thank you.
Add another condition to test the input. For example you can do this.
...
try{
cin >> number;
if (!cin) {
//error msg here
break;
} else if (number < 0 || number > 12)
...