Parsing Multiple Inputs

The I/O Stream Class Library input streams determine when to stop reading input into a variable based on the type of variable being read and the contents of the stream. The easiest way to understand how input is parsed is to write a simple program such as the following, and run it several times with different inputs.

#include <iostream.h>
void main() {
   int a,b,c;
   cin >> a >> b >> c;
   cout << "a: <" << a << ">\n"
        << "b: <" << b << ">\n"
        << "c: <" << c << '>' << endl;
}

The following table shows sample inputs and outputs, and explains the outputs. In the "Input" column, <\n> represents a new-line character in the input stream.

Input Output Remarks
123<\n>
No output. a has been assigned the value 123, but the program is still waiting on input for b and c.
1<\n> ,br 2<\n>
3<\n>
a: <1>
b: <2>
c: <3>
White space (in this case, new-line characters) is used to delimit different input variables.
1 2 3<\n> a: <1>
b: <2>
c: <3>
White space (in this case, spaces) is used to delimit different input variables. There can be any amount of white space between inputs.
123,456,789<\n>
a: <123>
b:
<-559038737>
c:
<- 559038737>
Characters are read into int a up to the first character that is not acceptable input for an integer (the comma). Characters are read into int b where input for a left off (the comma). Because a comma is not one of the allowable characters for integer input, ios::failbit is set, and all further input fails until ios::failbit is cleared.
1.2 2.3<\n>
3.4<\n>
a: <1>
b:
<-559038737>
c:
<-559038737>
As with the previous example, characters are read into a until the first character is encountered that is not acceptable input for an integer (in this case, the period). The next input of an int causes ios::failbit to be set, and so both it and the third input result in errors.