Validate cin is positive double in C++ [duplicate] - c++

How would I check if the input is really a double?
double x;
while (1) {
cout << '>';
if (cin >> x) {
// valid number
break;
} else {
// not a valid number
cout << "Invalid Input! Please input a numerical value." << endl;
}
}
//do other stuff...
The above code infinitely outputs the Invalid Input! statement, so its not prompting for another input. I want to prompt for the input, check if it is legitimate... if its a double, go on... if it is NOT a double, prompt again.
Any ideas?

Try this:
while (1) {
if (cin >> x) {
// valid number
break;
} else {
// not a valid number
cout << "Invalid Input! Please input a numerical value." << endl;
cin.clear();
while (cin.get() != '\n') ; // empty loop
}
}
This basically clears the error state, then reads and discards everything that was entered on the previous line.

failbit will be set after using an extraction operator if there was a parse error, there are a couple simple test functions good and fail you can check. They are exactly the opposite of each other because they handle eofbit differently, but that's not an issue in this example.
Then, you have to clear failbit before trying again.
As casablanca says, you also have to discard the non-numeric data still left in the input buffer.
So:
double x;
while (1) {
cout << '>';
cin >> x;
if (cin.good())
// valid number
break;
} else {
// not a valid number
cout << "Invalid Input! Please input a numerical value." << endl;
cin.clear();
cin.ignore(100000, '\n');
}
}
//do other stuff...

I would use:
double x;
while (!(std::cin >> x)) {
std::cin.clear();
std::cin.ignore(2147483647, '\n');
std::cout << "Error.\n";
}
or
double x;
while ((std::cout << "> ") && !(std::cin >> x)) {
std::cin.clear();
std::cin.ignore(2147483647, '\n');
std::cout << "Error.\n";
}

#include <iostream>
#include <string>
bool askForDouble(char const *question, double &ret)
{
using namespace std;
while(true)
{
cout << question << flush;
cin >> ret;
if(cin.good())
{
return true;
}
if(cin.eof())
{
return false;
}
// (cin.fail() || cin.bad()) is true here
cin.clear(); // clear state flags
string dummy;
cin >> dummy; // discard a word
}
}
int main()
{
double x;
if(askForDouble("Give me a floating point number! ",x))
{
std::cout << "The double of it is: " << (x*2) << std::endl;
} else
{
std::cerr << "END OF INPUT" << std::endl;
}
return 0;
}

bool is_double(double val)
{
bool answer;
double chk;
int double_equl = 0;
double strdouble = 0.0;
strdouble = val;
double_equl = (int)val;
chk = double_equl / strdouble;
if (chk == 1.00)
{
answer = false; // val is integer
return answer;
} else {
answer = true; // val is double
return answer;
}
}

One way is to check for floating number equality.
double x;
while (1) {
cout << '>';
cin >> x;
if (x != int(x)) {
// valid number
break;
} else {
// not a valid number
cout << "Invalid Input! Please input a numerical value." << endl;
}
}

Related

std::cin skipped after for loop [duplicate]

I'm working through a text book for self study. I can do the while loop no problem, but I have no idea how to do the terminating character.
Here is what I have now:
#include "../../std_lib_facilities.h" // Supplied by book author
int main()
{
int ii = 0;
int yy = 0;
bool test = true;
cout << "Enter two ints" << endl;
while (test)
{
cin>>ii, cin>>yy;
// this if statement doesn't work
if (ii == '|' || yy == '|')
{
test = false;
}
// this if statement catches all bad input, even the terminating '|'
if (cin.fail())
{
cout << "bad input";
cin.clear();
cin.ignore();
continue;
}
else
cout << ii << yy << endl;
}
return 0;
}
Streams can be a little confusing if you're unfamiliar with them. It's a large topic that's just going to require more research. Here's an example that should work, to hopefully get you started.
int main(int argc, char* argv[])
{
bool test = true;
while ( test ) {
std::cout << "Enter two integers> ";
int x, y;
// if this fails, stream is bad.
// #note this will fail for any input which cannot be interpreted
// as an integer value.
if (std::cin >> x >> y) {
std::cout << x << " " << y << std::endl;
}
else {
// clear stream error state so we can read from it again.
std::cin.clear();
// check for terminating character; else unknown.
if (std::cin.get() == '|')
std::cout << "Terminator found, exiting." << std::endl;
else
std::cerr << "Error: bad input, exiting." << std::endl;
// in either case the loop terminates.
test = false;
}
}
return 0;
}
Hope this helps. Good luck.
Use the cin.peek() function as follows, before you input the two numbers:
c=(cin >> ws).peek();
if(c=='|')
{
cout<<"exiting";return 1;
}
Note: (cin>>ws) is to get rid of leading whitespaces. Also, c is of type char.
The complete code now looks like this:
int main()
{
int ii = 0;
int yy = 0;
bool test = true;
cout << "Enter two ints" << endl;
while (test)
{
char c;
c=(cin >> ws).peek();
if(c=='|')
{
cout<<"exiting";return 1;
}
cin>>ii, cin>>yy;
if (cin.fail())
{
cout << "bad input";
cin.clear();
cin.ignore();
continue;
}
else
cout << ii << yy << endl;
}
return 0;
}

How to write a while loop that takes two ints and terminates with '|' in c++?

I'm working through a text book for self study. I can do the while loop no problem, but I have no idea how to do the terminating character.
Here is what I have now:
#include "../../std_lib_facilities.h" // Supplied by book author
int main()
{
int ii = 0;
int yy = 0;
bool test = true;
cout << "Enter two ints" << endl;
while (test)
{
cin>>ii, cin>>yy;
// this if statement doesn't work
if (ii == '|' || yy == '|')
{
test = false;
}
// this if statement catches all bad input, even the terminating '|'
if (cin.fail())
{
cout << "bad input";
cin.clear();
cin.ignore();
continue;
}
else
cout << ii << yy << endl;
}
return 0;
}
Streams can be a little confusing if you're unfamiliar with them. It's a large topic that's just going to require more research. Here's an example that should work, to hopefully get you started.
int main(int argc, char* argv[])
{
bool test = true;
while ( test ) {
std::cout << "Enter two integers> ";
int x, y;
// if this fails, stream is bad.
// #note this will fail for any input which cannot be interpreted
// as an integer value.
if (std::cin >> x >> y) {
std::cout << x << " " << y << std::endl;
}
else {
// clear stream error state so we can read from it again.
std::cin.clear();
// check for terminating character; else unknown.
if (std::cin.get() == '|')
std::cout << "Terminator found, exiting." << std::endl;
else
std::cerr << "Error: bad input, exiting." << std::endl;
// in either case the loop terminates.
test = false;
}
}
return 0;
}
Hope this helps. Good luck.
Use the cin.peek() function as follows, before you input the two numbers:
c=(cin >> ws).peek();
if(c=='|')
{
cout<<"exiting";return 1;
}
Note: (cin>>ws) is to get rid of leading whitespaces. Also, c is of type char.
The complete code now looks like this:
int main()
{
int ii = 0;
int yy = 0;
bool test = true;
cout << "Enter two ints" << endl;
while (test)
{
char c;
c=(cin >> ws).peek();
if(c=='|')
{
cout<<"exiting";return 1;
}
cin>>ii, cin>>yy;
if (cin.fail())
{
cout << "bad input";
cin.clear();
cin.ignore();
continue;
}
else
cout << ii << yy << endl;
}
return 0;
}

How can you make input take strings and int? c++

is it possible, say your trying to do calculations so the primary variable type may be int... but as a part of the program you decide to do a while loop and throw an if statement for existing purposes.
you have one cin >> and that is to take in a number to run calculations, but you also need an input incase they want to exit:
Here's some code to work with
#include <iostream>
using namespace std;
int func1(int x)
{
int sum = 0;
sum = x * x * x;
return sum;
}
int main()
{
bool repeat = true;
cout << "Enter a value to cube: " << endl;
cout << "Type leave to quit" << endl;
while (repeat)
{
int input = 0;
cin >> input;
cout << input << " cubed is: " << func1(input) << endl;
if (input = "leave" || input = "Leave")
{
repeat = false;
}
}
}
I'm aware they wont take leave cause input is set to int, but is it possible to use a conversion or something...
another thing is there a better way to break the loop or is that the most common way?
One way to do this is read a string from cin. Check its value. If it satisfies the exit condition, exit. If not, extract the integer from the string and proceed to procss the integer.
while (repeat)
{
string input;
cin >> input;
if (input == "leave" || input == "Leave")
{
repeat = false;
}
else
{
int intInput = atoi(input.c_str());
cout << input << " cubed is: " << func1(intInput) << endl;
}
}
You can read the input as a string from the input stream. Check if it is 'leave' and quit.. and If it is not try to convert it to a number and call func1.. look at atoi or boost::lexical_cast<>
also it is input == "leave" == is the equal operator. = is an assignment operator.
int main() {
cout << "Enter a value to cube: " << endl;
cout << "Type leave to quit" << endl;
while (true)
{
string input;
cin >> input;
if (input == "leave" || input == "Leave")
{
break;
}
cout << input << " cubed is: " << func1(atoi(input.c_str())) << endl;
}
}
you can use like
int input;
string s;
cint>>s; //read string from user
stringstream ss(s);
ss>>input; //try to convert to an int
if(ss==0) //not an integer
{
if(s == "leave") {//user don't want to enter further input
//exit
}
else
{
//invalid data some string other than leave and not an integer
}
}
else
{
cout<<"Input:"<<input<<endl;
//input holds an int data
}

Integer validation for input

I tried to prompt user for input and do the validation. For example, my program must take in 3 user inputs. Once it hits non-integer, it will print error message and prompt for input again. Here is how my program going to be look like when running :
Enter number: a
Wrong input
Enter number: 1
Enter number: b
Wrong input
Enter number: 2
Enter number: 3
Numbers entered are 1,2,3
And here is my code:
double read_input()
{
double input;
bool valid = true;
cout << "Enter number: " ;
while(valid){
cin >> input;
if(cin.fail())
{
valid = false;
}
}
return input;
}
My main method:
int main()
{
double x = read_input();
double y = read_input();
double z = read_input();
}
When my first input is non-integer, the program just exits by itself. It does not ask for prompting again. How could I fixed it? Or am I supposed to use a do while loop since I asking for user input.
Thanks in advance.
When the reading fails, you set valid to false, so the condition in the while loop is false and the program returns input (which is not initialized, by the way).
You also have to empty the buffer before using it again, something like:
#include <iostream>
#include <limits>
using namespace std;
double read_input()
{
double input = -1;
bool valid= false;
do
{
cout << "Enter a number: " << flush;
cin >> input;
if (cin.good())
{
//everything went well, we'll get out of the loop and return the value
valid = true;
}
else
{
//something went wrong, we reset the buffer's state to good
cin.clear();
//and empty it
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Invalid input; please re-enter." << endl;
}
} while (!valid);
return (input);
}
Your question did get myself into other issues like clearing the cin on fail() --
double read_input()
{
double input;
int count = 0;
bool valid = true;
while(count != 3) {
cout << "Enter number: " ;
//cin.ignore();
cin >> input;
if(cin.fail())
{
cout << "Wrong Input" <<endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
else
count++;
}
return input;
}
The problem is in the while condition
bool valid = true;
while(valid){
You loop until you get a non valid input, this absolutly not what you want! loop condition should be like this
bool valid = false;
while(! valid){ // repeat as long as the input is not valid
Here is a modified version of your read_double
double read_input()
{
double input;
bool valid = false;
while(! valid){ // repeat as long as the input is not valid
cout << "Enter number: " ;
cin >> input;
if(cin.fail())
{
cout << "Wrong input" << endl;
// clear error flags
cin.clear();
// Wrong input remains on the stream, so you need to get rid of it
cin.ignore(INT_MAX, '\n');
}
else
{
valid = true;
}
}
return input;
}
And in your main you need to ask for as may doubles as you want, for example
int main()
{
double d1 = read_input();
double d2 = read_input();
double d3 = read_input();
cout << "Numbers entered are: " << d1 << ", " << d2 << ", " << d3 << endl;
return 0;
}
You may also want to have a loop where you call read_double() and save the returned values in an array.

How to catch this exception C++

I'd like to catch exception which occurs when somebody gives not a number value on the cin so the program will read next value.
#include <iostream>
using namespace std;
int main()
{
int x = 0;
while(true){
cin >> x;
cout << "x = " << x << endl;
}
return 0;
}
If you really want to use exception handling, you could do something like this:
cin.exceptions(ios_base::failbit); // throw on rejected input
try {
// some code
int choice;
cin >> choice;
// some more code
} catch(const ios_base::failure& e) {
cout << "What was that?\n";
break;
}
Reference: http://www.cplusplus.com/forum/beginner/71540/
There is no exception being thrown at all. Instead, cin sets a "bad input" flag of sorts. What you want is this:
while ((std::cout << "Enter input: ") && !(std::cin >> x)) {
std::cin.clear(); //clear the flag
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); //discard the bad input
std::cout << "Invalid input; please re-enter.\n";
}
This series of questions explains it really well.
Links:
clear()
ignore()
Add something like:
if(cin.fail())
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),' ');
cout << "Please enter valid input";
}
int main()
{
int x = 0;
cin.exceptions(ios::failbit);
while(true){
try
{
cin>>x;
}
catch(ios_base::failure& e)
{
//..
}
cout<<"x = "<<x<<endl;
}
return 0;
}
This should work.