Made something like this:
int main()
{
while (true)
{
std::cout << "Enter a number between one and nine. \n";
int oneandnine;
std::cin >> oneandnine;
if (std::cin.fail())
{
std::cin.clear();
std::cin.ignore(100, '\n');
std::cout << "INVALID UNPUT!\n";
}else if (oneandnine <= 9 && oneandnine >= 1)
{
break;
}else
{
std::cout << "INVALID UNPUT!\n";
}
}
return 0;
}
and when input is provided something like this 456aihdb, getting something like this:
INVALID UNPUT!
Enter a number between one and nine.
INVALID UNPUT!
Enter a number between one and nine.
Why does it loop twice like this? is it because when the 456 is discarded and the rest aihdb isn't which causes it to loop again and skip a cin input?
It is exactly as you think it is.
The fail flag isn't set immediately, instead the formatted input operator reads the integer 456 into oneandnine, but doesn't set the fail flag since it's a valid integer value. That leads to the else case executing since std::cin.fail() is false and oneandnine is not between 1 and 9.
The next iteration you read the invalid input and the fail flag will be set leading to the second error output.
One common way to handle validation is to read the whole line into a string, put that string into an std::istringstream and use that to attempt to parse the input:
if (!std::getline(std::cin, line))
{
// Failure of some kind, could be EOF or something else
// Probably best not to continue in this case
}
std::istringstream iss(line);
if (!(iss >> oneandnine))
{
// Invalid input, report it as such
}
if (oneandnine < 1 || oneandnine > 9)
{
// Invalid number, report it as such
}
// Correct input, continue with program
Note that input such as 6abc will be considered valid by the above code. The 6 will be extracted into oneandnine and the abc part will silently be discarded. If that's not wanted there are other ways for the parsing (e.g. std::stoi or std::strtol if exceptions are not wanted). Do that instead of the >> extraction, but the rest of the code above should be fine.
std::istream's operator >> doesn't read in whole lines. It reads until it finds an invalid character or whitespace, if it has found a valid character before the invalid character the read operation succeeds and the invalid character is left in the stream.
In your example the first iteration successfully reads 456 and leaves aihdb in the stream. This fails your range check and the second iteration then tries to read the remaining characters which fails as the first character isn't a number.
If you want to read whole lines use std::getline then parse the whole line into a number. For example:
#include <iostream>
#include <string>
using std::cout;
int main()
{
while (true)
{
std::cout << "Enter a number between one and nine. \n";
std::string line;
std::getline(std::cin, line);
int oneandnine;
size_t pos;
try
{
oneandnine = std::stoi(line, &pos);
}
catch ( std::exception& )
{
oneandnine = -1;
}
if (pos != line.size() || oneandnine > 9 || oneandnine < 1)
{
std::cout << "INVALID INPUT!\n";
}
else
{
break;
}
}
return 0;
}
Related
In my case, I have to make sure the user input is either 1 or 2, or 3.
Here's my code:
#include <iostream>
using namespace std;
void invalid_choice_prompt() {
string msg = "\nInvalid Command! Please try again.";
cout << msg << endl;
}
int ask_user_rps_check_input(int user_choice) {
if (user_choice == 1 || user_choice == 2 || user_choice == 3) return 1;
return 0;
}
int ask_user_rps() {
// ask user's choice of Rock or Paper or Scissors
while (1) {
string msg =
"\nPlease enter your choice:\nRock - 1\nPaper - 2\nScissors - 3";
cout << msg << endl;
int user_choice;
cin >> user_choice;
if (ask_user_rps_check_input(user_choice)) {
return user_choice;
}
invalid_choice_prompt();
}
}
int main() {
ask_user_rps();
return 0;
}
The code is capable to handle the situation when the input is an integer, but when the input are characters or strings, the program will be trapped in the infinite loop.
Is there any elegant way to do this? I've found some methods about using cin.ignore to ignore the specified length of io buffer, but I don't think this method is flexible enough. I am looking for a more flexible solution.
I think an option would be to collect the user input to a string and then move it to stringstream using getline kind of like this:
std::string input;
std::getline(std::cin, input);
//Now check if the input is correct. if it is, then:
std::stringstream stream;
stream << input;
int num;
stream >> num;
I'm not sure if this is a good method but it works.
One of the simplest solution would be to check the cin stream failure something like below:
int ask_user_rps() {
// ask user's choice of Rock or Paper or Scissors
while (1) {
string msg =
"\nPlease enter your choice:\nRock - 1\nPaper - 2\nScissors - 3";
cout << msg << endl;
int user_choice;
cin >> user_choice;
if(cin.fail()) {
invalid_choice_prompt();
std::cin.clear();
std::cin.ignore(256,'\n');
continue;
}
if (ask_user_rps_check_input(user_choice)) {
return user_choice;
}
invalid_choice_prompt();
}
}
Reading from a stream using operator >> takes as many characters from the stream as the target type accepts; the rest will remain in the stream for subsequent reads. If the input has a format error (e.g. a leading alphabetical characters when an integer is expected), then an error-flag is set, too. This error-flag can be checked with cin.fail(). It remains set until it gets explicitly cleared. So if your code is...
int user_choice;
cin >> user_choice;
and if you then enter something that is not a number, e.g. asdf, then user_choice has an undefined value, an error-flag cin.fail() is (and reamins) set. So any subsequent read will fail, too.
To overcome this, you have to do three things:
First, check the error-flag. You can do this either through calling cin.fail() after a read attempt of through checking the return value of the expression (cin >> user_choice), which is the same as calling cin.fail().
Second, in case of an error, you need to clear the error-flag using cin.clear(). Otherwise, any attempt to read in anything afterwards will fail.
Third, if you want to continue with reading integral values, you need to take the invalid characters from the stream. Otherwise, you will read in asdf into a variable of type integer again and again, and it will fail again and again. You can use cin.ignore(numeric_limits<streamsize>::max(),'\n'); to take all characters until EOF or an end-of-line from the input buffer.
The complete code for reading an integral value with error-handling could look as follows:
int readNumber() {
int result;
while (!(cin >> result)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Input is not a number." << std::endl;
}
return result;
}
Take input as char
string user_choice;
cin >> user_choice;
check input is valid or not if(user_choice=='1')
Under windows10 and VS2017:
I was trying to read a double number 1.1 from keyboard using istream and put it into a int type variable, say temp. In reason temp is 1 but the istream seems to be stuck in some error status. In expectancy istream should stop and wait for keyboard input but it continues another round read-from-buffer and error occurs this time.
I had checked the rdstate() and it was equal to 2 after the 2nd round read-from-buffer. I know it was abnormal but why?
To replicate, run the code, type 1.1 in console and hit enter, the error will show up.
Actually, I used int32 to try to store double for some reasons. The program is supposed to print valid input from keyboard. Here valid refers to that the input should not exceed the range of int32 or be double/readable character. Otherwise the program should print Invalid input on the screen.
#include <iostream>
std::istream& f(std::istream &in) {
int temp = 0;
while(true) {
while (in >> temp) {
if (temp == -1) {
break;
}
std::cout << temp << std::endl;
}
if (in.eof()|| temp == -1) break;
if (!in) {
std::cout << "Invalid input" << std::endl;
in.clear();
in.ignore(10000,32);
}
}
in.seekg(0, std::ios::beg);
return in;
}
int main(){
std::cout << "Please input some integers and end with ^Z or -1" << std::endl;
f(std::cin);
return 0;
}
Keep in mind that when you read 1.1 from the keyboard you're reading text. The program looks at that text and decides what value it represents, depending on the type of the variable that you're reading into. If you're reading into an int, the input routine reads the first '1', then sees '.', which can't be part of the text representation of an int, and it stops reading. Your variable gets the value 1. If you try to read another int from the same input stream, that '.' will stop the read immediately, since it can't be part of an int, and the attempted input fails.
Short answer: don't do that. If your input text looks like floating-point, read it as floating-point.
Try this:
#include <iostream>
std::istream& f(std::istream &in) {
std::string temp = "";
while(true) {
while (in >> temp) {
if (temp == "-1") {
break;
}
std::cout << temp << std::endl;
}
if (in.eof()|| temp == "-1") break;
if (!in) {
std::cout << "Invalid input" << std::endl;
in.clear();
in.ignore(10000,32);
}
}
in.seekg(0, std::ios::beg);
return in;
}
int main(){
std::cout << "Please input some integers and end with ^Z or -1" << std::endl;
f(std::cin);
return 0;
}
You are parsing character by character from the buffer. You cannot put a character into an integer. You are assuming you are reading 1.1 from the stream, but you're instead reading 1,.,1 from the buffer, and the . is throwing the error. The above portion works as you are reading characters and keeping them in a string.
This function keeps getting called in another function inside a while-loop while valid_office_num is false. The problem is that if the input begins with a digit but is followed by other invalid characters (e.g. 5t) it takes the digit part and accepts that as a valid input. I want it to consider the whole input and reject it so it can ask for another one. I thought I could use getline() but then I cannot use cin.fail(). How could I implement this behavior?
I forgot to mention I am very new to C++, I have only learnt the basics so far.
(To be clear the desired behavior is to reject anything that contains anything other than digits. This is not an integer range check question. If it is NOT an integer, discard it and request another one)
//Function to read a valid office number, entered by user
int read_office_num()
{
//Declaration of a local variable
int office_num;
//Read input
cin >> office_num;
//Check if input was valid
if (cin.fail())
{
//Print error message
cout << "\nInvalid office number, it should only consist of digits!! Enter another:\n";
//Clear error flags
cin.clear();
//Ignore any whitespace left on input stream by cin
cin.ignore(256, '\n');
}
else
{
//Office number entered is valid
valid_office_num = true;
}
return office_num;
}
From what I gather you want the whole line to be read as a number and fail otherwise?
Well, you can use std::getline(), but you have to follow the algorithm below (I will leave the implementation to you..)
use std::getline(cin, str) to read a line, and if this returns true
use std::stoi(str, &pos) to convert to integer and get the position of the last integer
if pos != str.size() then the whole line in not an integer (or if the above throws an exception), then it's not a valid integer, else return the value...
Read a line of input as a std::string using std::getline().
Examine the string and check if it contains any characters that are not digits.
If the string only contains digits, use a std::istringstream to read an integer from the string. Otherwise report a failure, or take whatever other recovery action is needed (e.g. discard the whole string and return to read another one).
You could use a stringstream
int read_office_num()
{
//Declaration of a local variable
int office_num;
string input = "";
while (true) {
getline(cin, input);
stringstream myStream(input);
if (myStream >> office_num)
break;
cout << "\nInvalid office number, it should only consist of digits!! Enter another:\n" << endl;
}
return office_num;
}
If you want to reject input like 123 xxx you could add an additional check to verify that the received string is indeed an integer:
bool is_number(const string& s)
{
string::const_iterator itr = s.begin();
while (itr != s.end() && isdigit(*itr)) ++itr;
return !s.empty() && itr == s.end();
}
int read_office_num()
{
//Declaration of a local variable
int office_num;
string input = "";
while (true) {
getline(cin, input);
stringstream myStream(input);
if (is_number(input) && myStream >> office_num)
break;
cout << "\nInvalid office number, it should only consist of digits!! Enter another:\n" << endl;
}
return office_num;
}
You should probably just look at the number of input characters that are left in cin. You can do that with in_avail
Your function will probably end up having a body something like this:
//Declaration of a local variable
int office_num;
//Read input and check if input was valid
for (cin >> office_num; cin.rdbuf()->in_avail() > 1; cin >> office_num){
//Print error message
cout << "\nInvalid office number, it should only consist of digits!! Enter another:\n";
//Ignore any whitespace left on input stream by cin
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
//Office number entered is valid
valid_office_num = true;
return office_num;
Points of interest:
There is always at least 1 character in cin otherwise the cin would be marked as bad and that would not be good
You don't need valid_office_num if read_office_num is implemented this way, cause valid_office_num will always be set to true before returning
Hm. I may be missing something, but why not read a line, trim it, use regular expressions to validate a number and then exploit strstream's facilities or just atoi if you must? In all reality I'd probably just let users get away with extraneous input (but discard it if I'm sure I'm always running interactively). Following the motto "be lenient in what you accept."
The "interactive" caveat is important though. One can generally not assume that cin is a terminal. Somebody may get cocky and let your program run on a text file or in a pipeline, and then it would fail. A robust approach would separate data processing (portable) from means of input (possibly machine specific and therefore also more powerful and helpful than stdin/stdout via a console).
Here's how to do it using Boost Lexical Cast:
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <vector>
#include <string>
int read_office_num()
{
using boost::lexical_cast;
using boost::bad_lexical_cast;
using namespace std;
int office_num;
while (true)
{
try
{
string input = cin.getline();
office_num = lexical_cast<int>(*argv));
break;
}
catch(const& bad_lexical_cast)
{
cout << "\nInvalid office number, it should only consist of digits!! Enter another:\n";
}
}
return office_num;
}
In my simple Fraction class, I have the following method to get user input for the numerator, which works fine for checking garbage input like garbage, but will not recognize user input which starts with an integer, and is followed by garbage, 1 garbage or 1garbage.
void Fraction::inputNumerator()
{
int inputNumerator;
// loop forever until the code hits a BREAK
while (true) {
std::cout << "Enter the numerator: ";
// attempt to get the int value from standard input
std::cin >> inputNumerator;
// check to see if the input stream read the input as a number
if (std::cin.good()) {
numerator = inputNumerator;
break;
} else {
// the input couldn't successfully be turned into a number, so the
// characters that were in the buffer that couldn't convert are
// still sitting there unprocessed. We can read them as a string
// and look for the "quit"
// clear the error status of the standard input so we can read
std::cin.clear();
std::string str;
std::cin >> str;
// Break out of the loop if we see the string 'quit'
if (str == "quit") {
std::cout << "Goodbye!" << std::endl;
exit(EXIT_SUCCESS);
}
// some other non-number string. give error followed by newline
std::cout << "Invalid input (type 'quit' to exit)" << std::endl;
}
}
}
I saw a few posts on using the getline method for this, but they didn't compile when I tried them, and I'm having trouble finding the original post, sorry.
Better check as follows:
// attempt to get the int value from standard input
if(std::cin >> inputNumerator)
{
numerator = inputNumerator;
break;
} else { // ...
Or yes: Follow recommendations to parse a complete input line combining std::getline() and std::istringstream appropriately.
I basically want to validate that I have an int and not a floating point number. What I currently have is:
int den1;
cout << "Enter denominator of first fraction" << endl;
cin >> den1;
while (den1 == 0){
cout << "Enter a non-zero denominator" << endl;
cin >> den1;
}
Is there a "test" to generate a boolean value for den1 == int? I'm trying to avoid using getline() because I don't want to use a string if it isn't necessary.
If you want to force your input to be of an integer type, then use an integer type for your input. If den1 is an int, it will not let you put a floating point value in it. That is, cin >> den1 will be an int value. If the user tries to input 3.14159, only the 3 will be read (it will stop reading at the .. Note that the rest of the buffer will contain numbers as well, so if you don't clear it, the next attempt to read an integer will read 14159.
EDIT
If you want to "force" the user to enter a valid integer, you can do something like this:
std::string line;
int value = 0;
bool valid = false;
do
{
if (std::getline(std::cin, line))
{
if (std::string::npos == line.find('.'))
{
// no decimal point, so not floating point number
value = std::stol(line);
valid = true;
}
else
{
std::cin.clear();
}
}
} while (!valid);
Which is a lot of extra code compared to:
int value;
std::cin >> value;
You want to use something like
if (std::cin >> den) {
// process den
}
else {
// deal with invalid input
}
When an input operation fails, it sets std::ios_base::failbit on the stream and the stream converts to false instead of true. While the stream is in this failure mode, it won't read anything from the stream, i.e., the failure mode as to be cleared, e.g., using
std::cin.clear();
Once the failure mode is cleared, the offending character still sits in the stream. You can ignore the next character using, e.g.
std::cin.ignore();
or ignore all characters until the next newline:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
First of all, user input is always a string. Next, you need to define your goal more precisely. For example a reasonable thing to distinguish is whether the input can be parsed in its entirety as an integer, or as a floating point number, or neither. Here's one way to do this with iostreams, disregarding whitespace:
#include <iostream>
#include <sstream>
#include <string>
for (std::string line; std::getline(std::cin, line); )
{
std::istringstream iss1(line), iss2(line);
int n;
double x;
if (iss1 >> n >> std::ws && iss1.get() == EOF)
{
// have an int, use "n"
}
else if (iss2 >> d >> std::ws && iss2.get() == EOF)
{
// have a floating point number, use "d"
}
else
{
// failed to parse the input
continue;
}
}