Streams and Input Sources
An istringstream is a class for reading from a string stream, so it is the right choice when a program needs to interpret a string.
Why Text Needs a Stream
Many programs do not get their text from a keyboard typed straight into a console. A graphical user interface, or GUI, may hand the program a string, which is simply a sequence of characters. A string like that is easy to store, but it is not yet split into the values a program needs, such as a number followed by another number. This article shows how to treat such a string as an input source, so the program can read from it in the same way it reads from other input.
What do you think happens?
A program puts the string 42 Alice 3.5 into an istringstream and extracts an int, a string, and a double from it, one after another. What does a later call to str() on that same stream return?
Reveal answer
The whole original text 42 Alice 3.5
str() returns the text the stream holds as a whole. Extraction pulls individual values out one at a time, but it does not remove the text that the istringstream holds.
Where the Text in a Program Comes From
Think of a program that has two different kinds of input. One kind comes from the user typing at a console, which the program reads directly. The other kind is a string that a GUI has already captured and passed over. In the second case the program has the text, but the text is one long piece. A line such as 42 Alice 3.5 is a single string until something splits it into a whole number, a name, and a decimal number.
The source describes the solution in stages. First, the string arrives from the GUI. Second, the program places that string into an istringstream. Third, formatted input operations read values out of that stream and into the program's variables. The string never has to be handled as one block of characters that you take apart by hand. The stream does the splitting for you, using the same formatted input operations you already know.
What an istringstream Is
An istringstream is a class for reading from a string stream. It holds a string, and formatted input operations can pull values out of that string. It is the right choice when a program needs to interpret a string.
The name suggests its role. The 'i' indicates input, so the stream is for reading. The string you give it becomes the thing being read. Once a string has been placed into an istringstream, you do not need to write your own code to find the spaces and convert the pieces. The formatted input operations handle that work.
Tracing Values Out of One String
Take the GUI string 42 Alice 3.5. It is one sequence of characters. When it is placed into an istringstream, the program can ask the stream for an int, then a string, then a double. Each extraction takes the next piece of text, converts it to the requested type, and stores it in a variable. The diagram below shows how one string is divided into three typed values, and the order in which they are read.
Reading a GUI string into three variables
A GUI passes the string 42 Alice 3.5 to the program. The program needs an int, a string, and a double from it.
- 1Place the string into a stream
The string 42 Alice 3.5 is put into an istringstream. The stream now holds the whole text.
- 2Extract the first value
The first formatted input operation reads the next piece as an int. The piece 42 is stored in id.
- 3Extract the second value
The next operation reads the next piece as a string. The word Alice is stored in name, because the reading moves on past the first piece.
- 4Extract the third value
The last operation reads the next piece as a double. The number 3.5 is stored in score.
id holds 42, name holds Alice, and score holds 3.5.
Notice that the three extractions happen in a fixed order, from the first piece of text to the last. Reading the values out of the stream is a sequence of steps, and each step takes the next piece that has not yet been read.
Following the Read Position Through the Buffer
Each extraction starts from the point where the previous one stopped. Before any extraction, the stream is at the start of its text. After the first extraction takes 42, the next extraction begins with the text that follows it. After the second takes Alice, the third begins after that. The diagram below marks the state of the stream after each step.
Each arrow moves the read point forward. Earlier pieces are not read again, so the program never has to track positions in the text itself. The stream keeps track of where it is.
Retrieving the Whole Text with str()
The source notes that the result held by an istringstream can be read using str(). This is a different action from formatted input. Formatted input operations take values out of the stream one piece at a time. The str() call returns the text the istringstream holds as a whole string. Reading a value and retrieving the text are two separate things, and the code below shows both.
42|Alice|3.5
42 Alice 3.5- The string is placed into an istringstream named in.
- The >> operators extract an int, a string, and a double.
- The first line of output prints the three extracted values, separated by bars.
- The call
in.str()returns the whole text the stream holds, unchanged by the extractions.
| Action | What it returns | How much it takes | Typical use |
|---|---|---|---|
| Formatted input with >> | One typed value per operation | One piece of text at a time | Storing values in variables |
| str() on the istringstream | The whole text held by the stream | The entire string | Reading the text as a single string |
Values read out of a stream versus the text the stream holds
Two Directions: istringstream and ostringstream
An ostringstream works in the opposite direction. The source gives its common use as formatting something before handing the resulting string to a GUI. The stream collects formatted output, and the finished string is then passed on. The diagram below sets the two classes side by side.
Score: 3.5- Output is written into the ostringstream with the << operator.
str()returns the finished string, ready to be handed on.- Data moves out of the stream into a string, the reverse of the istringstream case.
Checking Your Understanding
A GUI hands your program the string 7 Ben 2.25. Describe the steps needed to store 7 in an int, Ben in a string, and 2.25 in a double. Then say what str() would return after those extractions, and whether an ostringstream or an istringstream is the right tool for this job.
Hints
- Start by thinking about which direction the data flows: the text comes in from the GUI and the values come out.
- Remember that extractions take pieces in order, from the first piece to the last.
str()returns the whole text the stream holds, not the separate values.
Mistakes Beginners Make with String Streams
Common mistake Using str() to get the separate values
What it looks likeCalling str() after reading and expecting it to return only the number 42.
Why it failsstr()returns the whole text the stream holds, not the individual values that were extracted.Do this insteadUse formatted input with >> to get each value, and use str() only when you want the whole text.
Common mistake Splitting the GUI string by hand when a stream can do it
What it looks likeSearching a string for spaces and converting each piece yourself.
Why it failsThe source describes placing the string into an istringstream so formatted input operations can read the values directly.
Do this insteadPlace the string into an istringstream and read the values with the formatted input operations you already know.
Common mistake Choosing the wrong stream class for the direction
What it looks likeUsing an ostringstream to read values out of text received from a GUI.
Why it failsAn ostringstream is for formatting output into a string, while an istringstream is a source you read from.
Do this insteadUse an istringstream when you need to interpret a string, and an ostringstream when you need to build a string to pass on.
Key Takeaways
- An istringstream is a class for reading from a string stream, and it is the right choice when a program needs to interpret a string.
- A string received from a GUI can be placed into an istringstream and then read with formatted input operations such as >>.
- Formatted input takes values out one piece at a time, while
str()returns the whole text the istringstream holds. - An istringstream reads from a string, while an ostringstream formats output into a string before it is given to a GUI.