Search

5.10 — std::cin, extraction, and dealing with invalid text input

Most programs that have a user interface of some kind need to handle user input. In the programs that you have been writing, you have been using std::cin to ask the user to enter text input. Because text input is so free-form (the user can enter anything), it’s very easy for the user to enter input that is not expected.

As you write programs, you should always consider how users will (unintentionally or otherwise) misuse your programs. A well-written program will anticipate how users will misuse it, and either handle those cases gracefully or prevent them from happening in the first place (if possible). A program that handles error cases well is said to be robust.

In this lesson, we’ll take a look specifically at ways the user can enter invalid text input via std::cin, and show you some different ways to handle those cases.

std::cin, buffers, and extraction

In order to discuss how std::cin and operator>> can fail, it first helps to know a little bit about how they work.

When we use operator>> to get user input and put it into a variable, this is called an “extraction”. operator>> is accordingly called the extraction operator when used in this context.

When the user enters input in response to an extraction operation, that data is placed in a buffer inside of std::cin. A buffer (also called a data buffer) is simply a piece of memory set aside for storing data temporarily while it’s moved from one place to another. In this case, the buffer is used to hold user input while it’s waiting to be extracted to variables.

When the extraction operator is used, the following procedure happens:

  • If there is data already in the input buffer, that data is used for extraction.
  • If the input buffer contains no data, the user is asked to input data for extraction (this is the case most of the time). When the user hits enter, a ‘\n’ character will be placed in the input buffer.
  • operator>> extracts as much data from the input buffer as it can into the variable (ignoring any leading whitespace characters, such as spaces, tabs, or ‘\n’).
  • Any data that can not be extracted is left in the input buffer for the next extraction.

Extraction succeeds if at least one character can be extracted from the input buffer. Any unextracted input is left in the input buffer for future extractions. For example:

If the user enters “5a”, 5 will be extracted, converted to an integer, and assigned to variable x. “a\n” will be left in the input stream for the next extraction.

Extraction fails if the input data does not match the type of the variable being extracted to. For example:

If the user were to enter ‘b’, extraction would fail because ‘b’ can not be extracted to an integer variable.

Validating input

The process of checking whether user input conforms to what the program is expecting is called input validation.

There are three basic ways to do input validation:

  • Inline (as the user types)
    • Prevent the user from typing invalid input in the first place.
  • Post-entry (after the user types)
    • Let the user enter whatever they want into a string, then validate whether the string is correct, and if so, convert the string to the final variable format.
    • Let the user enter whatever they want, let std::cin and operator>> try to extract it, and handle the error cases.

Some graphical user interfaces and advanced text interfaces will let you validate input as the user enters it (character by character). Generally speaking, the programmer provides a validation function that accepts the input the user has entered so far, and returns true if the input is valid, and false otherwise. This function is called every time the user presses a key. If the validation function returns true, the key the user just pressed is accepted. If the validation function returns false, the character the user just input is discarded (and not shown on the screen). Using this method, you can ensure that any input the user enters is guaranteed to be valid, because any invalid keystrokes are discovered and discarded immediately. Unfortunately, std::cin does not support this style of validation.

Since strings do not have any restrictions on what characters can be entered, extraction is guaranteed to succeed (though remember that std::cin stops extracting at the first non-leading whitespace character). Once a string is entered, the program can then parse the string to see if it is valid or not. However, parsing strings and converting string input to other types (e.g. numbers) can be challenging, so this is only done in rare cases.

Most often, we let std::cin and the extraction operator do the hard work. Under this method, we let the user enter whatever they want, have std::cin and operator>> try to extract it, and deal with the fallout if it fails. This is the easiest method, and the one we’ll talk more about below.

A sample program

Consider the following calculator program that has no error handling:

This simple program asks the user to enter two numbers and a mathematical operator.

Enter a double value: 5
Enter one of the following: +, -, *, or /: *
Enter a double value: 7
5 * 7 is 35

Now, consider where invalid user input might break this program.

First, we ask the user to enter some numbers. What if they enter something other than a number (e.g. ‘q’)? In this case, extraction will fail.

Second, we ask the user to enter one of four possible symbols. What if they enter a character other than one of the symbols we’re expecting? We’ll be able to extract the input, but we don’t currently handle what happens afterward.

Third, what if we ask the user to enter a symbol and they enter a string like “*q hello”. Although we can extract the ‘*’ character we need, there’s additional input left in the buffer that could cause problems down the road.

Types of invalid text input

We can generally separate input text errors into four types:

  • Input extraction succeeds but the input is meaningless to the program (e.g. entering ‘k’ as your mathematical operator).
  • Input extraction succeeds but the user enters additional input (e.g. entering ‘*q hello’ as your mathematical operator).
  • Input extraction fails (e.g. trying to enter ‘q’ into a numeric input).
  • Input extraction succeeds but the user overflows a numeric value.

Thus, to make our programs robust, whenever we ask the user for input, we ideally should determine whether each of the above can possibly occur, and if so, write code to handle those cases.

Let’s dig into each of these cases, and how to handle them using std::cin.

Error case 1: Extraction succeeds but input is meaningless

This is the simplest case. Consider the following execution of the above program:

Enter a double value: 5
Enter one of the following: +, -, *, or /: k
Enter a double value: 7

In this case, we asked the user to enter one of four symbols, but they entered ‘k’ instead. ‘k’ is a valid character, so std::cin happily extracts it to variable op, and this gets returned to main. But our program wasn’t expecting this to happen, so it doesn’t properly deal with this case (and thus never outputs anything).

The solution here is simple: do input validation. This usually consists of 3 steps:

1) Check whether the user’s input was what you were expecting.
2) If so, return the value to the user.
3) If not, tell the user something went wrong and have them try again.

Here’s an updated getOperator() function that does input validation.

As you can see, we’re using a while loop to continuously loop until the user provides valid input. If they don’t, we ask them to try again until they either give us valid input, shutdown the program, or destroy their computer.

Error case 2: Extraction succeeds but with extraneous input

Consider the following execution of the above program:

Enter a double value: 5*7

What do you think happens next?

Enter a double value: 5*7
Enter one of the following: +, -, *, or /: Enter a double value: 5 * 7 is 35

The program prints the right answer, but the formatting is all messed up. Let’s take a closer look at why.

When the user enters “5*7” as input, that input goes into the buffer. Then operator>> extracts the 5 to variable x, leaving “*7\n” in the buffer. Next, the program prints “Enter one of the following: +, -, *, or /:”. However, when the extraction operator was called, it sees “*7\n” waiting in the buffer to be extracted, so it uses that instead of asking the user for more input. Consequently, it extracts the ‘*’ character, leaving “7\n” in the buffer.

After asking the user to enter another double value, the “7” in the buffer gets extracted without asking the user. Since the user never had an opportunity to enter additional data and hit enter (causing a newline), the output prompts all get run together on the same line, even though the output is correct.

Although the above problem works, the execution is messy. It would be better if any extraneous characters entered were simply ignored. Fortunately, that’s easy to do:

Since the last character the user entered must be a ‘\n’, we can tell std::cin to ignore buffered characters until it finds a newline character (which is removed as well).

Let’s update our getDouble() function to ignore any extraneous input:

Now our program will work as expected, even if we enter “5*7” for the first input -- the 5 will be extracted, and the rest of the characters will be removed from the input buffer. Since the input buffer is now empty, the user will be properly asked for input the next time an extraction operation is performed!

Error case 3: Extraction fails

Now consider the following execution of the calculator program:

Enter a double value: a

You shouldn’t be surprised that the program doesn’t perform as expected, but how it fails is interesting:

Enter a double value: a
Enter one of the following: +, -, *, or /: Enter a double value: 

and the program suddenly ends.

This looks pretty similar to the extraneous input case, but it’s a little different. Let’s take a closer look.

When the user enters ‘a’, that character is placed in the buffer. Then operator>> tries to extract ‘a’ to variable x, which is of type double. Since ‘a’ can’t be converted to a double, operator>> can’t do the extraction. Two things happen at this point: ‘a’ is left in the buffer, and std::cin goes into “failure mode”.

Once in ‘failure mode’, future requests for input extraction will silently fail. Thus in our calculator program, the output prompts still print, but any requests for further extraction are ignored. The program simply runs to the end and then terminates (without printing a result, because we never read in a valid mathematical operation).

Fortunately, we can detect whether an extraction has failed and fix it:

That’s it!

Let’s integrate that into our getDouble() function:

Note: Prior to C++11, a failed extraction would not modify the variable being extracted to. This means that if a variable was uninitialized, it would stay uninitialized in the failed extraction case. However, as of C++11, a failed extraction will cause the variable to be zero-initialized. Zero initialization means the variable is set to 0, 0.0, “”, or whatever value 0 converts to for that type.

Error case 4: Extraction succeeds but the user overflows a numeric value

Consider the following simple example:

What happens if the user enters a number that is too large (e.g. 40000)?

Enter a number between -32768 and 32767: 40000
Enter another number between -32768 and 32767: The sum is: 0

In the above case, std::cin goes immediately into “failure mode”, so it does not assign a value to variable x. Consequently, x is left with the initialized value of 0. Additional inputs are skipped, leaving y with the initialized value of 0 as well. We can handle this kind of error in the same way as a failed extraction.

Putting it all together

Here’s our example calculator with full error checking:

Conclusion

As you write your programs, consider how users will misuse your program, especially around text input. For each point of text input, consider:

  • Could extraction fail?
  • Could the user enter more input than expected?
  • Could the user enter meaningless input?
  • Could the user overflow an input?

You can use if statements and boolean logic to test whether input is expected and meaningful.

The following code will test for and fix failed extractions or overflow:

The following will also clear any extraneous input:

Finally, use loops to ask the user to re-enter input if the original input was invalid.

Note: Input validation is important and useful, but it also tends to make examples more complicated and harder to follow. Accordingly, in future lessons, we will generally not do any kind of input validation unless it’s relevant to something we’re trying to teach.

5.11 -- Introduction to testing your code
Index
5.9 -- Random number generation

116 comments to 5.10 — std::cin, extraction, and dealing with invalid text input

  • Donlod

    When asking the user for input, the following code results in having to make an input at least twice.

    Using the debugger it seems that the line

    is  causing the problem. After it is executed i have to make an input. Then i have to make an input again for the actual cin >> number.

    • nascardriver

      Hi Donlod!

      @std::cin.clear clears the error flag. There's no reason to call it when no error occurred.
      @std::cin.ignore clears the input buffer. There's no reason to call it when there's no trailing data in the buffer.
      Change these things and your problem is gone.

      I can't find it in the documentation, but it seems as if calling functions that read from the input buffer when the input buffer is empty wait for input to be made.

      • Donlod

        Thanks for the reply.
        So is it possible to do this the "clean way"?
        I came up with two possible solutions:

        But if i remember correctly, we should avoid using break, continue in loops, right? Also i think the code is more self-explanatory when actually having a clearer loop condition.

        And this:

        Here i do not like the fact to check twice for cin.fail().

        • nascardriver

          > we should avoid using break, continue in loops, right?
          I can't find a rule for this and I don't see anything wrong with using break/continue.

          Your first solution is the better one, because, as you already said, you're checking twice in the second solution. There are three issues with it though
          * You're using an int for the while-loop's condition
          * You're using a magic number
          * You have duplicate code

          I don't think there's a nicer solution to this, but since this code is independent of the input extraction itself we can write a wrapper function for it so we don't need to repeat this all over the place.

          • Jack

            Would seem better to rename @cleanStream to something like notCleanStream, considering you are returning true if extraction fails. If extraction fails you do not have a cleanStream. Either that or change the function to return false if the extraction failed so the while loop reads as

            Thoughts?

            • nascardriver

              It's the verb "clean", not the adjective.

  • Joe

    Hi guys,

    I am having an issue with extraction handling.
    My issue is that it is not working.

    this is a snip of what I am trying and it does not handle my failures.  Anything I type, gets passed.

    • nascardriver

      Hi Joe!

      * Initialize your variables.
      * Don't use goto.

      Anything you can type can be converted to a char.
      Letters? Sure
      Numbers? Sure, a char is a number.
      Special characters? Yep, those fit in a char
      Strings? The first character can be extracted.

      If you only want to allow a specific subset of characters you'll need to filter them manually. eg. for only allowing lower case:

      Have a look at the ascii table to see the order of characters http://www.asciitable.com/

      • Joe

        Thank you again nascardriver.  I really appreciate the help and input.

        Tell me, what is the item with which you initialized char c with? \x00

        • nascardriver

          \x interprets the next two characters as a hexadecimal ascii code. So '\x00' is just 0, you could use 0, I use '\x00' when I use a char to hold a character and 0 when it holds a number, do what you like.

      • Joe

        Nevermind, I figured it out.  Thank you again.

        How about this?

        I know its clunky, but I have more to learn then I can cut it to better size.

        • Joe

          actually, this works

          • nascardriver

            Keep in mind that 32767 doesn't have any special effect to @std::cin.ignore. In a real program std::numeric_limits<std::streamsize>::max() should be used, this causes @std::cin.ignore to ignore everything up to the next newline.

  • Peter Baum

    "Error Case 3", code line 15:

    it wasn't clear to me why x was "good" after this failure.

    • nascardriver

      Hi Peter!

      • Peter Baum

        Hi nascardriver!  (Are you really a nascardriver?)

        I think the problem for me was the comment wording and the way it was laid out.  Perhaps the following will be clearer to some people:

  • WiseFool

    I have a question.  In this section we used cin.fail(), cin.clear(), and cin.ignore() functions, but where can I look to see what other similar associated functions that there might be for std::cin, and any other #include library commands, types or classes, and what they do and how they work?  (Also, I'm just curious - when we use std::cin, we don't need to add .function() or parenthetical parameters, so how does it just "know" to take input using the >> operator?  Is this just something built in to compilers to treat certain library things the same way they would a built-in operation?)  Thank you in advance for an answer.

    • nascardriver

      Hi WiseFool!

      cppreference and cplusplus have good documentations and examples to many functions.

      http://en.cppreference.com/w/cpp/io/basic_istream/ignore
      http://www.cplusplus.com/reference/istream/istream/ignore/

    • Peter Baum

      A great question.  It would be nice to include some of this information about documentation, as well as a little summary table of these functions/methods within the lesson.

  • Nick

    How's this for error handling (and code writing i.e any bad habits or better way to do it)?

    • nascardriver

      Hi Nick!

      I had to include two additional header to allow proper use of NaN. The same could be achieved by defining an arbitrary value to be used as NaN.

  • Sirius

    Very minor nitpick with the ordering of the error handling explanations; the 3rd and 4th single line error descriptions match up to the 4th and 3rd explanations. I.e.:

    "Input extraction succeeds but the user overflows a numeric value." - 3rd in list
    "Input extraction fails (e.g. trying to enter ‘q’ into a numeric input)." - 4th in list

    Then below:

    "Error case 3: Extraction fails" - matches 4th in list above
    (...some text...)
    "Error case 4: Extraction succeeds but the user overflows a numeric value" - matches 3rd in list above
    (...some text...)

    Sorry if I haven't made this very clear, or if it's intentional.

  • Michael

    Hi Alex,
    why ignore up to 32767 characters? what's special about this number?

    • Alex

      It's the largest 2-byte signed integer. We need a number larger than 1 just in case there are multiple characters to ignore. So what should we pick? 2? But what if there are 3 characters? 3? What if there are 4? So we pick the largest integer value that's guaranteed to fit in an integer.

  • Raj

    when the user enters 5*7 , y does *7/n remains in buffer and not only *7..why has the new line character appeared in the buffer without user sending it in cin?

    • Alex

      When you hit enter on your keyboard, that key is represented as a '\n' character in ASCII. Therefore, \n is in the buffer because you put it there. 🙂

  • Kewal

    What if I want to accept integers from the user until he enters space or presses enter twice, extraction doesn't fail in this case, how can I do it?

    • Alex

      This is an odd request, and I'm not sure why you'd want to do this. But my first thought is to read things in character by character, and reconstruct the integers the user is entering from the number characters.

  • Prashanth

    Hey, why do you use the number 32,767 exactly in cin.ignore() function. Does the number has to do anything with 'int' datatype?

  • antiriad7

    We use Enter button to confirm our input. Is there any other ways to confirm our input and make our program go to next step (I am trying to confirm input without trailing '\n')?

Leave a Comment

Put all code inside code tags: [code]your code here[/code]