Figure 19.12 demonstrates input from an istringstream
object. Lines 10–11 create string input
containing the data and istringstream
object inputString
constructed to contain the data in string input
. The string input
contains the data
Input test 123 4.7 A
which, when read as input to the program, consist of two strings ("Input"
and "test"
), an int
(123
), a double
(4.7
) and a char
('A'
). These characters are extracted to variables string1
, string2
, integer
, double1
and character
in line 18.
1 // Fig. 19.12: Fig19_12.cpp
2 // Demonstrating input from an istringstream object.
3 #include <iostream>
4 #include <string>
5 #include <sstream>
6 using namespace std;
7
8 int main()
9 {
10 string input( "Input test 123 4.7 A" );
11 istringstream inputString( input );
12 string string1;
13 string string2;
14 int integer;
15 double double1;
16 char character;
17
18 inputString >> string1 >> string2 >> integer >> double1 >> character;
19
20 cout << "The following items were extracted
"
21 << "from the istringstream object:" << "
string: " << string1
22 << "
string: " << string2 << "
int: " << integer
23 << "
double: " << double1 << "
char: " << character;
24
25 // attempt to read from empty stream
26 long value;
27 inputString >> value;
28
29 // test stream results
30 if ( inputString.good() )
31 cout << "
long value is: " << value << endl;
32 else
33 cout << "
inputString is empty" << endl;
34 } // end main
The data is then output in lines 20–23. The program attempts to read from inputString
again in line 27. The if
condition in line 30 uses function good
(Section 13.8) to test if any data remains. Because no data remains, the function returns false
and the else
part of the if
...else
statement is executed.