I have a simple function that accepts either 1 or 2 and reprompts for input if neither of those two numbers are entered. Right now, if I enter any number, it stays stuck on asking for valid input. I know it's something easy, but I'm not seeing it now. What am I missing?
#include <iostream>
#include <string>
using namespace std;
int userChoice();
int main()
{
userChoice();
return 0;
}
int userChoice()
{
int input = 0;
cout << "Enter 1 or 2: ";
cin >> input;
while (input != 1 || input != 2 || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.ignore(1000, '\n');
}
cout << "Enter only 1 or 2: ";
cin >> input;
}
return input;
}
The conditional in while is not formed correctly. It will be always true.
You need to use something like:
while ( !cin || (input != 1 && input != 2) )
Suggestion for change of strategy
I think it will be better to use a recursive function:
int userChoice()
{
int input = 0;
cout << "Enter 1 or 2: ";
cin >> input;
// If we get a valid input, return.
if ( cin && (input == 1 || input == 2))
{
return input;
}
// If there is any error in reading, clear the stream.
if ( !cin )
{
cin.clear();
cin.ignore(1000, '\n');
}
// Call function again.
return userChoice();
}
Change the while condition to
while( (input != 1 && input !=2) || cin.fail())
use && not ||
#include <iostream>
#include <string>
using namespace std;
int userChoice();
int main()
{
userChoice();
return 0;
}
int userChoice()
{
int input = 0;
cout << "Enter 1 or 2: ";
cin >> input;
while ((input != 1) && (input != 2))
{
if (cin.fail())
{
cin.clear();
cin.ignore(1000, '\n');
}
cout << "Enter only 1 or 2: ";
cin >> input;
}
return input;
}
Related
I wrote a function to squire number and try to cover all the input possibilities.
Overall it works fine with numeric input, but it starts a infinite loop of printing statements on screen when I enter alphabetical input.As all we know that inside computer single character like "A or a or b or B" so on is represented by integers and as i learned from my teacher that we can store single characters into a variable with integer data type. i am not talking about strings which means collection of characters . this program create problem with single character !
#include <iostream>
#include <string>
using namespace std;
void squire();
int main() {
squire();
}
void squire() {
double num = 1.0, pow = 1.0, Squire_Number = 1.0;
char ans;
reStart:
cout << "please Enter the Number: \n";
cin >> num;
cout << "please enter the nmber you want to power the number with: \n";
cin >> pow;
if (num > 0 && pow>0) {
for (int i = 1; i <= pow; i++) {
Squire_Number *= num;
}
cout << pow << " power of " << num << " is equil to : " << Squire_Number;
goto option;
}
else
{
cout << "Please enter Positve Integers. \n" ;
option:
cout<< "\nPease type 'Y' to Enter the values again OR type 'c' to Exit ! \n";
cin >> ans;
if (ans == 'y' || ans == 'Y') {
goto reStart;
} else if (ans == 'c' || ans == 'C') {
cout << "thank you for using our function. \n";
}
}
return;
}
Better try to read the input in an std::string, then parse the string to check if you only have numeric characters and then use std::atoi to convert the string in integer. One last recomendation, avoid to use goto instructions, this practice make a code difficult to read.
#include <iostream>
#include <string>
#include <cstdlib>
bool OnlyNumeric(const std::string& numStr)
{
size_t len= numStr.length();
int i;
for (i=0;i<len && numStr[i] <='9' && numStr[i] >='0';i++) ;
return i == len;
}
int main()
{
std::string inputStr;
int num;
do{
std::cout << "Input number:\n";
std::cin >> inputStr;
}
while (!(OnlyNumeric(inputStr) && (num=std::atoi(inputStr.c_str())) ));
std::cout << "Your number is : " << num;
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;
}
Trying to create a while loop that will re-ask to enter correct input. In this case, the correct input needs to be a number. When I test it and put in a non-number answer, it ends the program. The while loop isn't working.
if (variableQuestionsVf == "Yes" || variableQuestionsVf == "yes")
{
cout << "Input final velocity (in m/s): " ;
while (cin >> finalVelocity)
{
istringstream s(sVf);
s >> value;
if (value <= 0 || value >= 0) //Validating input for final velocity
break;
cout << "Please enter final velocity (in m/s): " ;
}
}
Is there an easier way?
I think you are validating your input incorrectly. Try doing something like this:
#include <iostream>
#include <limits>
int main()
{
int x;
std::cin >> x;
while(std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::cout << "Bad entry. Enter a NUMBER: ";
std::cin >> x;
}
}
Source
I don't know how to make a program which exit on pressing 'q' character.
I'm doing this :
#include <iostream>
#include <limits>
using namespace std;
int main()
{
double arg;
char c;
while (c!= 'q' && c != 'Q')
{
cout << "Please enter a number x (q = program quit) : " << endl;
cin >> arg;
if (cin.fail())
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
return 0;
}
Program doesn't exit on 'q' or 'Q'. It's just keep asking about "Please enter a number x (q = program quit) : ". How shall I do that ? Thanks
You have not read "c" in code.
#user1627167 thanks. It works. Code :
#include <iostream>
#include <limits>
#include <sstream>
using namespace std;
int main()
{
double arg;
string s;
while (s != "q" && s != "Q")
{
cout << "Please enter a number x (q = program quit) : " << endl;
cin >> s;
istringstream ss(s);
ss >> arg;
if (cin.fail())
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
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);
}