Stopping endless loop when int = (something that's not an integer) - c++

So this is a problem that I've been having since I started programming (Not that long ago. I still don't know why I started with C++). When I have some integer variables and the user's input defines them, if the user inputs something other than an integer the program freaks out and runs an endless loop of the last command it was given. I don't think sample code is needed but if it is I can make a basic example pretty easily.

If you want to know exactly what your mistake was, then we'd need to see your code, but the usual idiom is like this:
int i;
while (std::cin >> i) {
// do something with the user's input, i
}
if (std::cin.fail()) {
std::cout << "not a number!\n";
}
If failure occurs and you want to get past the invalid input so that the user can try again, first call cin.clear(), then either cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') to ignore the whole line, or std::string s; std::cin >> s; to ignore a whitespace-separated word.
Beware that because the second case actually constructs the string in memory, the user could input a few gigabytes without a space, and the program will fail. That's usually fine if the input is from a terminal, it's the user's own stupid fault. It might be less fine if the input is from an HTTP request or other untrusted source, so some time in future you might end up worrying about it...

Check this out Guess the number - Infinite loop when bad read

When programming always, and i mean always, validate your input.
Check if the input you get is sane.
What i mean by that if you get something that is supposed to be int check if it is.
Convert it if it is not.
If you get a string check if it is in bounds, meaning is it to long, to short, to whatever.
cin
Would be the Term to Google for in your case.

Related

Is there keyboard input that isn't considered a char?

Thanks for taking the time to read this first of all,
I'm currently writing a driver program for a class in C++ and I need some input from the user. I've started using typedef to create validation programs so I can switch between different types fairly easily. For the particular problem I'm working on, I've found that I'm only working with char which leads me to my questions:
My validation checks to see if the input is char. Is using validation pointless if I know I'm just working with char in particular? Everything that the user types in seems to be a char.
Is there anything that the user could type in that won't be considered a char?
This question may seem a bit trivial but I've never really thought about this before! Still learning the language, so any guidance is appreciated.
Code in question (ElementType is of type char):
void getInput( ElementType & cho )
{
while ( !(cin >> cho) )
{
cout<< "That is an invalid input..."
<< "\nTry again: ";
}
cout<< endl;
}
Is there anything that the user could type in that won't be considered a char?
Yes: Shift, Ctrl, Alt, Num Lock to name a few.
The point is that a keyboard is its own beast with a potential output for each key-press, key-release of every key. A keyboard driver (software) takes these events and translates them into a series of char for a program's cin/stdin. Alternatively, a program could get access to the low level events, but may be beyond standard C++ code.
Recommend staying with the model that cin receives sporadically any of the usually 256 different char including '\0' until program-end or cin is closed from some source be it a keyboard, re-directed file input, piped input, or a remote device. Ignore that idea that input usually comes from a keyboard. It is simply a sequence of char.
Is using validation pointless?
Validation is useful. Code should validate the char arriving per the requirements of the program - not the requirements of char. Example, code may have trouble handing a null character, a negative char, a char outside the ASCII range of 0 - 127, or too many char between line endings. Validating input makes code resilient against hackers who will exploit a vulnerable program.
Under Linux, with UTF-8 input, I can certainly type a lot of stuff that isn't a char. E.g. typing รก gives two bytes. There are quite a lot of others, directly typeable depending on the keyboard handling in place.
International character handling is complex. Not all the world types ASCII.

How to ignore line break after reading two ints with cin?

I am new to C++, I have practically started it today. Any way, I am facing a problem where the first line contains two integers, and the next lines contain operations to be done. It's a fairly weird problem, actually, so I won't go into the details. Well, I am having a problem with reading the first line, and then the follow up operations.
My code looks like this so far:
int m, j;
string comando;
string OPR
cin << m << l;
while (getline(cin, comando)) {
OPR = comando.substr(0, 3);
}
The problem is: Apparently, whenever I write both m and l in the same line, the \n stays in the buffer, and it get's read by the newline, causing a problem when I try to take the substring. I tried adding a char variable that would be read after m and l, which would, supposedly, get the \n. However, it is getting the first letter of the newline instead, which, then, messes up my code. I tried to see if I had any syntax errors or anything, but that isn't it. I also looked for ways to ignore the \n char, but everything I found was related to strings, or reading from files.
I know I could read the line, and then cast the two ints from string to int, but that seems like a bad way to do it (at least it would be a bad way to do it in C).
Anyways, if any one can help me, that would be awesome, thanks!
P.S.: I don't do a check before the substr operation because, by the definition of the problem, the line will have a 3-char operation, a space and then an integer.
A good place to look for tips for common problems like this is your favorite reference:
When used immediately after whitespace-delimited input, e.g. after int n; std::cin >> n;, getline consumes the endline character left on the input stream by operator>>, and returns immediately. A common solution is to ignore all leftover characters on the line of input with cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); before switching to line-oriented input.
From here.

How does program know to continue to new string?

When i use while(cin >> word) { cout << word } program shows all the word i write one by one. But i cant understand why. When we use ints we write something like i++ to end the loop. My question is how does the program knows to write the next word and not the first word over and over again?
cin >> word does two separate things; it reads a word from the input (changing the state of cin) and then tells you whether it succeeded (so the loop knows when to terminate). Next time round the loop cin knows what you've already read and moves on to the next thing.
So it's a function with side-effects; as well as returning a result it also alters the state of the system. There are two views of this - it's a very bad idea that makes understanding code hard, and it's very useful for writing simple but powerful code. Both are true to some extent.
Because the condition cin >> word is executed in each iteration of the loop. Thus before the cout statement becomes executed, the cin statement is executed, setting word to the current entered string.

How do I write exception handling for bad input?

I am trying to write a function that prompts a user for a five digit number, and I want to write an exception block to handle bad input incase the user tries to enter a string or some non-integer input.
I know how to write an exception handling block for something like a division function where you thrown an exception for the denominator being 0, but I have no clue how to do this for input that I have no control over.
First of all, I'd generally advise against this -- bad input from the user is nearly the rule rather than the exception.
If you insist on doing it anyway, you'd probably do it by accepting anything as input, and then throwing an exception when/if it's not what you want:
// Warning: untested code.
// Accepting negative numbers left as an exercise for the reader.
int get_int(std::istream &is) {
std::string temp;
std::getline(temp, is);
for (int i=0; i<temp.size(); i++)
if (!isdigit(temp[i]))
throw std::domain_error("Bad input");
return atoi(temp);
}
I repeat, however, that I don't think this is generally a good idea. I'd note (for one example) that iostreams already define a fail bit specifically for situations like this (and the normal operator>> to read an int uses that mechanism).
The most straightforward solution is to read a string, and convert it to integer, for example with atoi. If you get a zero as result, and your string was not "0", you know that the input was not numerical, without needing to loop through the string yourself.
Exceptions are often appropriate when accepting data from another machine or process, where there is no reason to expect invalid data to occur within an otherwise valid data stream. With regard to user input, exceptions should only be used in cases which should represent a clear departure from normal program flow. For example, if a program has a tty-style interface, and a routine which is supposed to read a line of input gets a control-C, it may be useful for such a routine to throw an exception. The control-C shouldn't necessarily end the program, but if the program is expecting to read several lines of input from the user, typing control-C at one should frequently cause the remainder to be skipped.

What is the best way to do input validation in C++ with cin?

My brother recently started learning C++. He told me a problem he encountered while trying to validate input in a simple program. He had a text menu where the user entered an integer choice, if they entered an invalid choice, they would be asked to enter it again (do while loop). However, if the user entered a string instead of an int, the code would break.
I read various questions on stackoverflow and told him to rewrite his code along the lines of:
#include<iostream>
using namespace std;
int main()
{
int a;
do
{
cout<<"\nEnter a number:"
cin>>a;
if(cin.fail())
{
//Clear the fail state.
cin.clear();
//Ignore the rest of the wrong user input, till the end of the line.
cin.ignore(std::numeric_limits<std::streamsize>::max(),\
'\n');
}
}while(true);
return 0;
}
While this worked ok, I also tried a few other ideas:
1. Using a try catch block. It didn't work. I think this is because an exception is not raised due to bad input.
2. I tried if(! cin){//Do Something} which didn't work either. I haven't yet figured this one out.
3. Thirdly, I tried inputting a fixed length string and then parsing it. I would use atoi(). Is this standards compliant and portable? Should I write my own parsing function?
4. If write a class that uses cin, but dynamically does this kind of error detection, perhaps by determining the type of the input variable at runtime, would it have too much overhead? Is it even possible?
I would like to know what is the best way to do this kind of checking, what are the best practices?
I would like to add that while I am not new to writing C++ code, I am new to writing good standards compliant code. I am trying to unlearn bad practices and learn the right ones. I would be much obliged if answerers give a detailed explanation.
EDIT: I see that litb has answered one of my previous edits. I'll post that code here for reference.
#include<iostream>
using namespace std;
int main()
{
int a;
bool inputCompletionFlag = true;
do
{
cout<<"\nEnter a number:"
cin>>a;
if(cin.fail())
{
//Clear the fail state.
cin.clear();
//Ignore the rest of the wrong user input, till the end of the line.
cin.ignore(std::numeric_limits<std::streamsize>::max(),\
'\n');
}
else
{
inputCompletionFlag = false;
}
}while(!inputCompletionFlag);
return 0;
}
This code fails on input like "1asdsdf". I didn't know how to fix it but litb has posted a great answer. :)
Here is code you could use to make sure you also reject things like
42crap
Where non-number characters follow the number. If you read the whole line and then parse it and execute actions appropriately it will possibly require you to change the way your program works. If your program read your number from different places until now, you then have to put one central place that parses one line of input, and decides on the action. But maybe that's a good thing too - so you could increase the readability of the code that way by having things separated: Input - Processing - Output
Anyway, here is how you can reject the number-non-number of above. Read a line into a string, then parse it with a stringstream:
std::string getline() {
std::string str;
std::getline(std::cin, str);
return str;
}
int choice;
std::istringstream iss(getline());
iss >> choice >> std::ws;
if(iss.fail() || !iss.eof()) {
// handle failure
}
It eats all trailing whitespace. When it hits the end-of-file of the stringstream while reading the integer or trailing whitespace, then it sets the eof-bit, and we check that. If it failed to read any integer in the first place, then the fail or bad bit will have been set.
Earlier versions of this answer used std::cin directly - but std::ws won't work well together with std::cin connected to a terminal (it will block instead waiting for the user to input something), so we use a stringstream for reading the integer.
Answering some of your questions:
Question: 1. Using a try catch block. It didn't work. I think this is because an exception is not raised due to bad input.
Answer: Well, you can tell the stream to throw exceptions when you read something. You use the istream::exceptions function, which you tell for which kind of error you want to have an exception thrown:
iss.exceptions(ios_base::failbit);
I did never use it. If you do that on std::cin, you will have to remember to restore the flags for other readers that rely on it not throwing. Finding it way easier to just use the functions fail, bad to ask for the state of the stream.
Question: 2. I tried if(!cin){ //Do Something } which didn't work either. I haven't yet figured this one out.
Answer: That could come from the fact that you gave it something like "42crap". For the stream, that is completely valid input when doing an extraction into an integer.
Question: 3. Thirdly, I tried inputting a fixed length string and then parsing it. I would use atoi(). Is this standards compliant and portable? Should I write my own parsing function?
Answer: atoi is Standard Compliant. But it's not good when you want to check for errors. There is no error checking, done by it as opposed to other functions. If you have a string and want to check whether it contains a number, then do it like in the initial code above.
There are C-like functions that can read directly from a C-string. They exist to allow interaction with old, legacy code and writing fast performing code. One should avoid them in programs because they work rather low-level and require using raw naked pointers. By their very nature, they can't be enhanced to work with user defined types either. Specifically, this talks about the function "strtol" (string-to-long) which is basically atoi with error checking and capability to work with other bases (hex for example).
Question: 4. If I write a class that uses cin, but dynamically do this kind of error detection, perhaps by determining the type of the input variable at runtime, will it have too much overhead? Is it even possible?
Answer: Generally, you don't need to care too much about overhead here (if you mean runtime-overhead). But it depends specifically on where you use that class. That question will be very important if you are writing a high performance system that processes input and needs to have high throughout. But if you need to read input from a terminal or a file, you already see what this comes down to: Waiting for the user to input something takes really so long, you don't need to watch runtime costs at this point anymore on this scale.
If you mean code overhead - well it depends on how the code is implemented. You would need to scan your string that you read - whether it contains a number or not, whether some arbitrary string. Depending on what you want to scan (maybe you have a "date" input, or a "time" input format too. Look into boost.date_time for that), your code can become arbitrarily complex. For simple things like classifying between number or not, I think you can get away with small amount of code.
This is what I do with C but it's probably applicable for C++ as well.
Input everything as a string.
Then, and only then, parse the string into what you need. It's sometimes better to code your own than try to bend someone else's to your will.
In order to get the exceptions with iostreams you need to set the proper exception flag for the stream.
And I would use get_line to get the whole line of input and then handle it accordingly - use lexical_cast, regular expressions (for example Boost Regex or Boost Xpressive, parse it with Boost Spirit, or just use some kind of appropriate logic
What I would do is twofold: First, try to validate the input, and extract the data, using a regular expression, if the input is somewhat not trivial. It can be very helpful also even if the input is just a series of numbers.
Then, I like to use boost::lexical_ cast, that can raise a bad_ lexical_ cast exception if the input cannot be converted.
In your example:
std::string in_str;
cin >> in_str;
// optionally, test if it conforms to a regular expression, in case the input is complex
// Convert to int? this will throw bad_lexical_cast if cannot be converted.
int my_int = boost::lexical_cast<int>(in_str);
Forget about using formatted input (the >> operator) directly in real code. You will always need to read raw text with std::getline or similar and then use your own input parsing routines (which may use of the >> operator) to parse the input.
How about a combination of the various approaches:
Snag the input from std::cin using std::getline(std::cin, strObj) where strObj is a std::string object.
Use boost::lexical_cast to perform a lexical translation from strObj to either a signed or unsigned integer of largest width (e.g., unsigned long long or something similar)
Use boost::numeric_cast to cast the integer down to the expected range.
You could just fetch the input with std::getline and then call boost::lexical_cast to the appropriately narrow integer type as well depending on where you want to catch the error. The three step approach has the benefit of accepting any integer data and then catch narrowing errors separately.
I agree with Pax, the simplest way to do this is to read everything as string, then use TryParse to verify the input. If it is in the right format, then proceed, otherwhise just notify the user and use continue on the loop.
One thing that hasn't been mentioned yet is that it is usually important that you test to see if the cin >> operation worked before using the variable that supposedly got something from the stream.
This example is similar to yours, but makes that test.
#include <iostream>
#include <limits>
using namespace std;
int main()
{
while (true)
{
cout << "Enter a number: " << flush;
int n;
if (cin >> n)
{
// do something with n
cout << "Got " << n << endl;
}
else
{
cout << "Error! Ignoring..." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
return 0;
}
This will use the usual operator >> semantics; it will skip whitespace first, then try to read as many digits as it can and then stop. So "42crap" will give you the 42 then skip over the "crap". If that isn't what you want, then I agree with the previous answers, you should read it into a string and then validate it (perhaps using a regular expression - but that may be overkill for a simple numeric sequence).