validating if value enter is an integer - c++

First of all I am new to C++, can you guys help me with validating if value enter is an integer? And if my while statement in int(main) can be replace with a function.
#include <iostream>
using namespace std;
int validateNumb (int numb, int lim){
//takes a num, limit and checks if number is within limit
while (numb>=lim) { //if outside limit
cout << "Invalit input, try again with number (less than " << lim <<"): ";
cin >> numb; //assign user input value
}
cout << "Your integer is: " << numb << "\n\n"; //display input value
return numb;
}
int main() {
//variables
int num1, num2, num3, sum;
int limnum1, limnum2, limnum3;
//Welcome message
cout << "Hello & Welcome to E&M Ls1\n\n\n";
//First Number
cout << "Please Define the limit for First integer: ";
while (!(cin >> limnum1)) //if input is not true
{
cout << "Error!! Invalit input, please enter the First integer: ";
cin.clear();
cin.ignore(50, '\n');
}
cout << "Please Enter the First Integar that is (less than " << limnum1 << "): ";
while (!(cin >> num1)) //if input is not true
{
cout << "Error!! Invalit input, please enter the First integer: ";
cin.clear();
cin.ignore(50, '\n');
}
num1 = validateNumb(num1, limnum1); //check condition
//Second Number
cout << "Please Define the limit for Second integer: ";
while (!(cin >> limnum2)) //if input is not true
{
cout << "Error!! Invalit input, please enter the Second integer: ";
cin.clear();
cin.ignore(50, '\n');
}
cout << "Please Enter the Second Integar that is (less than " << limnum2 << "): ";
while (!(cin >> num2)) //if input is not true
{
cout << "Error!! Invalit input, please enter the Second integer: ";
cin.clear();
cin.ignore(50, '\n');
}
num2 = validateNumb(num2, limnum2); //check condition
//Third Number
cout << "Please Define the limit for Third integer: ";
while (!(cin >> limnum3)) //if input is not true
{
cout << "Error!! Invalit input, please enter the Third integer: ";
cin.clear();
cin.ignore(50, '\n');
}
cout << "Please Enter the Third Integar that is (less than " << limnum3 << "): ";
while (!(cin >> num3)) //if input is not true
{
cout << "Error!! Invalit input, please enter the Third integer: ";
cin.clear();
cin.ignore(50, '\n');
}
num3 = validateNumb(num3, limnum3); //check condition
//Sum for num1+num2+num3
sum = num1+num2+num3;
cout << "Sum of " << num1 <<" & " << num2 <<" & " << num3 <<" is: " << sum << ""; //display input value
cout<<"_______________________"<<endl;
cout<<"Thank you & Goodbye"<<endl; //end of the program
return 0;
}

bool is_integer(float k)
{
return std::floor(k) == k;
}
This solution should work for all possible values of k. I am pretty sure this is a case where you can safely compare floats using ==.
and yes your main can be broken into functions, maybe something like...
int getFirstNumber(){
int num =0;
// copy your code to get the first number
return num;
}
int getSecondNumber(){
int num =0;
// copy your code to get the second number
return num;
}
int getThirdNumber(){
int num =0;
// copy your code to get the thirdnumber
return num;
}
int sum(int a,int b,int c){
return (a+b+c);
}
int main(){
int a,b,c,d =0;
a = getFirstNumber;
b = getSecondNumber;
c = getThirdNumber;
d = sum(a,b,c);
return 0;
}
EDIT: I see you want to check if the number is in a valid range...
here:
// Returns true if x is in range [low..high], else false
bool inRange(unsigned low, unsigned high, unsigned x)
{
return ((x-low) <= (high-low));
}

Related

how to make cin only accept a single character and int accept only numbers?

How can I make cin accept only a single letter in char datatypes and numbers only in double/int datatypes.
#include <iostream>
using namespace std;
int main (){
char opt;
int num1, num2, sum;
cout << "A. Addition" << endl << "B. Subtraction" << endl;
cout << "Enter option: "; cin >> opt;
//if I put "ab" here, I want to make cin only read the first letter if possible.
switch(opt){
case 'A': case 'a':{
cout << "Enter first number: "; cin >> num1; //accept numbers only
cout << "Enter second number: "; cin >> num2;//accept numbers only
sum = num1+num2;
cout << "The sum is " << sum;
break;
}
}
}
By definition, operator>> reading into a char will read in exactly 1 character, leaving any remaining input in the buffer for subsequent reading. You have to validate the read is successful and the character is what you are expecting before using it.
And likewise, operator>> reading into an int will read in only numbers. You have to validate the read is successful before using the number, and discard any unused input if the read fails to return a valid number.
Try something like this:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
char ReadChar(const char* prompt) {
string s;
do {
cout << prompt << ": ";
if (!(cin >> s)) throw ...;
if (s.length() == 1) break;
//cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Enter a single character" << endl;
}
while (true);
return s[0];
}
char ReadInt(const char* prompt) {
int value;
do {
cout << prompt << ": ";
if (cin >> value) break;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Enter a valid number" << endl;
}
while (true);
return value;
}
int main() {
char opt;
int num1, num2, result;
cout << "A. Addition" << endl << "B. Subtraction" << endl;
opt = ReadChar("Enter option");
switch (opt) {
case 'A': case 'a': {
num1 = ReadInt("Enter first number");
num2 = ReadInt("Enter second number");
result = num1 + num2;
cout << "The sum is " << result << endl;
break;
}
case 'B': case 'b': {
num1 = ReadInt("Enter first number");
num2 = ReadInt("Enter second number");
result = num1 - num2;
cout << "The difference is " << result << endl;
break;
}
default: {
cout << "Invalid option" << endl;
break;
}
}
}

I ask for a number in this code, what should I do in case the user gives a letter instead?

The problem is what should I do to prevent the user to put a char instead of a number in floats h,a,b,A or B
I've tried using typeid, but I don't know how that works
int main() {
float h, a, b, A, B;
std::cout << "Llena los datos, si no tienes algĂșn dato, escribe 0\n";
std::cout<<"Hipotenusa:";
std::cin >> h;
std::cout<<"Lado a: ";
std::cin>> a;
std::cout<<"Lado b: ";
std::cin>> b;
std::cout<<"Angulo A: ";
std::cin>> A;
std::cout<<"Angulo B: ";
std::cin>> B;
}
If the user gives a char value for one of the variables, I expect an output of "Incorrect Value", which is "Datos Incorrectos" in spanish.
There is a simple way but not the best, Just you want a loop which takes the input then check whether the input is a number or not and if not, prints the input message again until the user input a number.
float Number;
cout << "Please enter a number: ";
while (!(cin >> Number)) {
cout << "Error: Please enter a number: ";
// clears the error flag
cin.clear();
// Throw away a specific number of characters from the input stream
cin.ignore(INT_MAX, '\n');
}
Look at my else if statement. It doesnt include variable declarations.
{
cout << "Input correct sales tax ( .08 or .12 for example. ) : ";
cin >> salesTax;
if ((salesTax < 0)||(salesTax > 1))
{
cout << invalid << endl << "\nRestarting...\n";
fnInitiateRegister();
return 0;
}
else if (cin.fail()) // HERE IS YOUR ANSWER
{
cout << invalid << "Needs to be a numeric value.\n";
return 0;
} // HERE IS WHERE YOUR ANSWER ENDS.
else
{
cout << "Proceeding to cart\n";
fnNumberOfCartItems();
} return 0;
}

input validation in loop

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

how do you do a integer validation in C++?

ok, I have been looking for days now but I cant find anything that will work.
I have a program and I want to make sure that the user enters a integer and not a double.
this program works fine but I need to validate the numOne and numTwo to make sure they are integers and not doubles, (5.5)
int main()
{ //This is where my variables are stored
int numOne, numTwo, answer, rightAnswer, ranNumOne, ranNumTwo;
//this will display to the user to enter a range of numbers to be used
cout << "Please enter a set of numbers to be the range for the problems." << endl;
cout << "Please enter the beginning number." << endl;
cin >> numOne;
cout << "please enter the ending number." << endl;
cin >> numTwo;
//this makes sure that the user entered a integer(if not the program will close)
if (!(cin >> numOne))
{
cout << "You did not enter a integer PLEASE RE-RUN THE PROGRAM AND TRY AGAIN!" << endl;
cin.clear();
cin.ignore(100, '\n');
exit(0);
}
cout << "please enter the ending number." << endl;
cin >> numTwo;
//this makes sure that the user entered a number(if not the program will close)
if (!(cin >> numTwo))
{
cout << "You did not enter a integer PLEASE RE-RUN THE PROGRAM AND TRY AGAIN!" << endl;
cin.clear();
cin.ignore(100, '\n');
exit(0);
}
//this is where the first number is generated
srand(time(0));
ranNumOne = rand() % (numOne - numTwo) + 1;
system("PAUSE");
//this is where the second number is generated
srand(time(0));
ranNumTwo = rand() % (numOne - numTwo) + 1;
//this is where the calculations are done
rightAnswer = ranNumOne + ranNumTwo;
//this displays the problem that was generated
cout << "What is: " << endl;
cout << setw(11) << ranNumOne << endl;
cout << setw(6) << "+" << setw(3) << ranNumTwo << endl;
cout << " -------\n";
cin >> answer;
//this checks to see if the answer is right or not and displays the result
if (answer == rightAnswer)
{
cout << "Your answer was correct! " << endl;
}
else
cout << "The correct answer is: " << rightAnswer << endl;
return 0;
}
Use std:n:ci.fail() to see if it failed.
int numOne;
cin >> numOne;
if(cin.fail())
cout << "Not a number...")
Maybe even a nice template function.
template<typename T>
T inline input(const std::string &errmsg = "") {
T var;
std::cin >> var;
while (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(256, '\n');
std::cout << errmsg;
std::cin >> var;
}
return var;
}
Or not:
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <ctime>
#define DIFF(n1, n2) (n1 > n2 ? n1 - n2 : n2 - n1)
using namespace std;
int input(const string &firstmsg = "", const string &errmsg = "") {
int var;
std::cout << firstmsg;
std::cin >> var;
while (cin.fail()) {
cin.clear();
cin.ignore(256, '\n');
cout << errmsg;
cin >> var;
}
return var;
}
int main(){
//This is where my variables are stored
int numOne, numTwo, answer, rightAnswer, ranNumOne, ranNumTwo;
//this will display to the user to enter a range of numbers to be used
cout << "Please enter a set of numbers to be the range for the problems." << endl << endl;
numOne = input("Please enter the beginning number: ", "Invalid. Enter again: ");
//this asks the user for the second number
numTwo = input("Please enter the ending number: ", "Invalid. Enter again: ");
//this is where the first number is generated
srand(time(0));
ranNumOne = rand() % (DIFF(numOne, numTwo)) + 1; // ensures it will always be positive
system("PAUSE");
//this is where the second number is generated
srand(time(0));
ranNumTwo = rand() % (DIFF(numOne, numTwo)) + 1;
//this is where the calculations are done
rightAnswer = ranNumOne + ranNumTwo;
//this displays the problem that was generated
cout << "What is: " << endl;
cout << setw(11) << ranNumOne << endl;
cout << setw(6) << "+" << setw(3) << ranNumTwo << endl;
cout << " -------\n";
cin >> answer;
//this checks to see if the answer is right or not and displays the result
if (answer == rightAnswer){
cout << "Your answer was correct! " << endl;
}
else
cout << "The correct answer is: " << rightAnswer << endl;
return 0;
}
why not, get the number into a double and then see if that double is an int. ie
double d;
cin>>d;
if (ceil(d) != d)
cout >> " not an integer";

Why cant i reject Decimals? (C++)

With this code:
#include <iostream>
#include <iomanip>
using namespace std;
//Functions
int power(int base,int exp);
double energy(int z, int n);
//Main
int main() {
const double E0(13.6),hce(1.24E-6),e(1.6E-19);
int n1,n2,z;
double E;
cout << "**************************************" << endl;
cout << "Welcome to the energy level calculator\n" << endl;
cout << "Please enter the atomic number, z: " << endl;
cin >> z; //Ask for z
cout << "Please enter n for the initial energy level: " << endl;
cin >> n1; //Ask for n1
cout << "Please enter n for the final energy level: " << endl;
cin >> n2; //Ask for n2
while(cin.fail()||z<1||n1<1||n2<1){
cout << "\n\n\n\n\nPlease enter non-zero integers only, try again\n\n\n\n\n\n" << endl;
cout << "**************************************" << endl;
cin.clear();
cin.ignore();
cout << "Please enter the atomic number, z: " << endl;
cin >> z; //Ask for z
cout << "Please enter n for the initial energy level: " << endl;
cin >> n1; //Ask for n1
cout << "Please enter n for the final energy level: " << endl;
cin >> n2; //Ask for n2
}
etc...
The program is only allowed to accept Integers
If i enter a decimal, such as 1.2 the program rejects the 1. but uses the 2 as z when it should be asking for input from the keyboard?
Can anyone help?
Since you asked for an explanation, when you enter 1.2
cin >> z; //Successfully reads '1' into 'z'
cin >> n1; //Fails to read '.' into 'n1'. '.' remains the first character in the stream.
cin >> n2; //Fails to read '.' into 'n2'. '.' remains the first character in the stream.
You then loop back to the beginning of your loop.
cin.clear(); //clears the fail flag from the two previous failed inputs
cin.ignore(); // ignores the '.'
cin >> z; //Reads '2' into 'z'. The stream is now empty.
The program then blocks on cin >> n1 waiting for more characters to be placed in the stream.
After each input, you should see if the input failed.
cin>>n1;
if(cin.fail())
cin.ignore();