The user should input a double but how would I get the program to ignore a string or a char if they put one in. The problem with my current code is when I put in a string the program will spam and fill the screen with the cout << "What is the length of the rectangle";
double length;
do {
cout << "What is the length of the rectangle: ";
cin >> length;
bString = cin.fail();
} while (bString == true);
do {
cout << "What is the length of the rectangle: ";
cin >> length;
bString = cin.fail();
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
} while (bString == true);
This is the code I found that works for my issue.
cin.fail() will not differentiate between integers and floating point numbers.
The best way to check is by using std::fmod() function to check if the reminder is more than zero. if it is then its a floating point number.
Here is the code
#include <cmath>
int main()
{
double length;
std::cout <<"What is the length of the rectangle: ";
std::cin >> length;
if (std::cin.fail())
{
std::cout<<"Wrong Input..."<<std::endl;
} else
{
double reminder = fmod(length, 1.0);
if(reminder > 0)
std::cout<<"Yes its a number with decimals"<<std::endl;
else
std::cout<<"Its NOT a decimal number"<<std::endl;
}
}
Beware that this code will not differentiate between 12 and 12.0.
If the user inputs an invalid data type, cin will fail. You can check using this
double length;
while(true)
{
std::cout << "What is the length of the rectangle: ";
std::cin >> length;
if (std::cin.fail())
{
std::cout << "Invalid data type...\n";
std::cin.clear();
std::cin.ignore();
}
else
{
break;
}
}
Related
void biggest_number() {
float first_input;
float big_num;
float input;
cout <<"\n You've chosen to Find out The Biggest Number. Type in number to compare\nType 0 if you want to stop the function.\nFirst number : ";
cin >> first_input;
first_input = big_num;
//cout << first_input;
while (1) {
cin >> input;
if (big_num < input) {
input = big_num;
}
else if (input == 0) {
cout << big_num;
break;
}
else{
}
};
};
So I've written a function to find the biggest number. But whatever I put as an input, big_num always comes out as 0.
I've tried to use cout <<first_input << big_num; in order to find out where the function doesn't work. You can see from the comment. That part doesn't work and I couldn't figure out why.
You have the assignment first_input = big_num; reversed. It should be big_num = first_input;
float big_num;
You declare big_num but haven't assigned it a value, so big_num is uninitialized. So big_num can hold any value. Then, you assign first_input to equal big_num. So both first_input and big_num is holding random values.
It seems kind of strange to me that you input first_input, then immediately you assign first_input to equal big_num. I think that you meant the other way around.
big_num = first_input;
Also:
void biggest_number() {
float first_input;
float big_num;
float input;
cout <<"\n You've chosen to Find out The Biggest Number. Type in number to compare\nType 0 if you want to stop the function.\nFirst number : ";
cin >> first_input;
first_input = big_num;
//cout << first_input;
while (1) {
cin >> input;
if (big_num < input) {
input = big_num;
}
else if (input == 0) {
cout << big_num;
break;
}
else{
}
}; // <-- here
}; // <-- and here
There is two unnecessary semicolons. You should remove it.
note: using namespace std; is bad practice, so avoid using it.
void biggest_number()
{
float first_input;
float big_num;
float input;
cout <<"\n You've chosen to Find out The Biggest Number. Type in number to compare\nType 0 if you want to stop the function.\nFirst number : ";
cin >> first_input;
big_num = first_input;
cout << "Second number :";
while (1)
{
cin >> input;
if (first_input < input)
{
big_num = input;
cout<< big_num << " Is the big number" << endl;
break;
}
else if (input == first_input)
{
cout << "Both inputs are same" << endl;
break;
}
else
{
cout<< big_num << "Is the big number" << endl;
break;
}
}
}
int main()
{
cout<<"Hello World";
biggest_number();
return 0;
}
See #justANewbie's answer about the actual problem (mixing up your input and big_num variables).
I just wanted to provide a more compact solution. It's not important that the code is short in this case, but you might learn some more convenient C++ coding tricks/styles from it. Additionally, it's sometimes easier to spot errors when the code is compact and has less branching.
This solution uses a common C++ pattern you might call "read while":
#include <cmath> // for INFINITY
#include <iostream>
void biggest_number() {
float biggest = -INFINITY;
// while we can read a number and it's not zero
for (float input; (std::cin >> input) && input != 0; ) {
// keep track of biggest number found
if (input > biggest) biggest = input;
}
std::cout << biggest;
}
I have this snippets of code from my original long program, and as much as it looks simple, it doesn't work correctly! I am brand-new to c++ language, but I know in Java that would be the way to do it (Regardless of the syntax).
Simply put, this should ask the user for an input to answer the following multiplication (5*5), however, it should also check if the user entered a wrong input (not number), keep asking the user again and again... Somehow, it keeps running forever without taking a new input!!
I hope to get, not only an answer, but also a reason for such an error!
int main() {
int userAnswer;
bool isValidAnswer = true;
cout << 5 << " * " << 5 << " = ";
cin >> userAnswer;
cin.ignore();
do {
if (cin.fail()) { //user input is not an integer
cout << "Your answer is not valid! Please enter only a natural number: ";
cin >> userAnswer;
cin.ignore();
} else {
isValidAnswer = false;
}
} while (isValidAnswer);
return 0;
}
Well you need to clear the error state before accepting new input. Call cin.clear() then cin.ignore() before trying to read input again.
I would do something like.
cout << "Enter a number: ";
cin >> number;
while(cin.fail())
{
cin.clear();
cin.ignore(1000, '\n'); //some large number of character will stop at new line
cout << "Bad Number Try Again: ";
cin >> number;
}
First, cin.fail() is not going to adequately check if your answer is a natural number or not with the type set to int (could also be negative).
Second, your boolean isValidAnswer is really checking if it's is an invalid answer.
Third (and most importantly), as another answer suggests, you should put in cin.clear() to clear the failure state, and then followed by cin.ignore(), which will remove the failed string from cin.
Fourth, cin will only check if an int exists somewhere in the string. You'll need to perform your own string comparison to determine if the entire input is a int (see answer below, based on this answer).
Updated:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
bool isNum(string line)
{
char* p;
strtol(line.c_str(), &p, 10);
return *p == 0;
}
int main() {
int userAnswer;
string input;
bool isInvalidAnswer = true;
cout << 5 << " * " << 5 << " = ";
while (isInvalidAnswer) {
if (!(cin >> input) || !isNum(input)) {
cout << "Answer is not a number! Please try again:\n";
cin.clear();
cin.ignore();
}
else {
userAnswer = atoi(input.c_str());
if (userAnswer < 0) { //user input is not an integer
cout << "Answer is not a natural number! Please try again:\n";
} else {
isInvalidAnswer = false;
}
}
}
cout << "Question answered!\n";
return 0;
}
I am trying to practice my input validation in C++. How can i let the program validate the user input when a user is asked to enter a number or string?
Here is a sample of my code.
public:
void CreateProduct() {
inputProduct:
system("cls");
cout << "\n\n\n\n\n\n\n\t\t\t\tPLEASE PROVIDE ACCURATE INFORMATION";
cout << "\n\n\t\tPRODUCT NUMBER: ";
cin >> ProductNumber;
if (!cin) {
cout << "\nPlease provide an integer";
cin.clear();
cin.end;
goto inputProduct;
//when enter a string i should enter this if statement and exit
// to be asked for another entry but am getting stuck in a loop.
}
system("cls");
cout << "\n\n\n\n\n\n\n\t\t\t\tPRODUCT NAME: ";
cin >> ProductName;
system("cls");
cout << "\n\n\n\n\n\n\n\t\t\t\tPRICE: ";
cin >> Price;
system("cls");
}
Please help me understand this input validation.
You can check whether input is number or not by checking ascii value of each character in input .
#include <iostream>
#include <cstring>
#include <string>
int main(void)
{
std::string str;
std::cin>>str;
bool isNumeric = true;
for(size_t i=0;i<str.length();++i)
{
if(str[i]< '0' || str[i] > '9')
{
isNumeric = false;
break;
}
}
if(!isNumeric)
{
std::cout<<"Input is not an integer";
exit(1);
}
return 0;
}
I am trying to make a cin where the user can only enter 0 to 1. If the user doesnt enter those numbers then he should get an error saying "Please enter within the range of 0 to 1."
But its not working.
What am i doing wrong?
int alphaval = -1;
do
{
std::cout << "Enter Alpha between [0, 1]: ";
while (!(std::cin >> alphaval)) // while the input is invalid
{
std::cin.clear(); // clear the fail bit
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore the invalid entry
std::cout << "Invalid Entry! Please Enter a valid value: ";
}
}
while (0 > alphaval || 1 < alphaval);
Alpha = alphaval;
Try this:
int alphaval;
cout << "Enter a number between 0 and 1: ";
cin >> alphaval;
while (alphaval < 0 || alphaval > 1)
{
cout << "Invalid entry! Please enter a valid value: ";
cin >> alphaval;
}
If you want to trap empty lines I'd use std::getline and then parse the string to see if the input is valid.
Something like this:
#include <iostream>
#include <sstream>
#include <string>
int main()
{
int alphaval = -1;
for(;;)
{
std::cout << "Enter Alpha between [0, 1]: ";
std::string line;
std::getline(std::cin, line);
if(!line.empty())
{
std::stringstream s(line);
//If an int was parsed, the stream is now empty, and it fits the range break out of the loop.
if(s >> alphaval && s.eof() && (alphaval >= 0 && alphaval <= 1))
{
break;
}
}
std::cout << "Invalid Entry!\n";
}
std::cout << "Alpha = " << alphaval << "\n";
return 0;
}
If you want a different prompt on error then I'd put the initial prompt outside the loop and change the inner prompt to what you prefer.
Week one of C++, starting with Peggy Fisher's Learning C++ on Lynda.com.
This is what I came up with. Love to receive feedback.
int GetIntFromRange(int lower, int upper){
//variable that we'll assign input to
int input;
//clear any previous inputs so that we don't take anything from previous lines
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//First error catch. If it's not an integer, don't even let it get to bounds control
while(!(cin>>input)) {
cout << "Wrong Input Type. Please try again.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
//Bounds control
while(input < lower || input > upper) {
cout << "Out of Range. Re-enter option: ";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//Second error catch. If out of range integer was entered, and then a non-integer this second one shall catch it
while(!(cin>>input)) {
cout << "Wrong Input Type. Please try again.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
//return the cin input
return input;
}
As the exercise was to order Hamburgers, this is how I ask for the amount:
int main(){
amount=GetIntFromRange(0,20);
}
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.