Concepts / Formatted Input Operations

Formatted Input Operations

The stream collects formatted output, and the finished string is then passed on.

  • Programming

Text That Arrives Without Being Typed

Many programs never see their input typed directly into a console. A graphical user interface, or GUI, may hand the program a string instead. A string is simply a sequence of characters. That string can be stored without any trouble, but it is not yet split into the values the program needs, such as a number followed by another number.

This article introduces a way to treat such a string as an input source. Once the string is placed into a special kind of stream, the program can read from it in the same manner it reads from other input. The tool for this job is the istringstream, and the formatted input operations you already know can pull values out of it.

What an istringstream Is

Definition

An istringstream is a class for reading from a string stream. It is the right choice when a program needs to interpret a string, that is, to find out what values the string contains.

Key point

The direction of the data is the most important thing to remember. An istringstream is a source you read from. The text goes into the stream first, and then the program takes pieces of it out. Because of this direction, it is the natural choice whenever you start with a string and want its contents.

The benefit of wrapping a string in a stream is that the program does not have to treat the string as one block of characters that it parses by hand. Instead, the same formatted input operations used on other input sources can be applied to the text. The stream does the work of moving through the characters and handing back separate values.

Receiving Text from a GUI

The source describes a specific situation: a string received from a GUI can be read with formatted input operations once it has been put into an istringstream. The flow runs in three 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.

GUI text fieldhands over a stringstd::string linestored, not yet splitistringstream intext placed in the streamint afirst valuedouble bsecond valuestd::string wthird valuestring arrivesplaced into stream>> extracts>> extracts>> extracts
How does one long text string travel through an istringstream and become separate typed variables?

Read the diagram from left to right. The text field supplies the string, the string is stored, and the stream receives it. The formatted input operations then take the values out one at a time and deliver them into variables whose types match what the program expects. The string itself is never split by the programmer's own loop.

Pulling Values Out With Formatted Input

Suppose a GUI hands the program the text 42 3.5 hello. The program wants an integer, a floating-point number, and a word. The code below places the string into an istringstream and reads the three values with the same extraction operator used for console input.

cpp
Output
42 3.5 hello
Notes on the code
  • The string is wrapped in an istringstream named in
  • The >> operator extracts an int, then a double, then a string
  • Each variable receives the next piece of text, converted to its type
Worked example

Reading a GUI string with three fields

A GUI hands over the string 7 2.25 blue. Show how the program obtains an int, a double, and a string.

  1. 1
    Store the string

    The text 7 2.25 blue is kept in a std::string, which is ready to use but not yet split.

  2. 2
    Place it into a stream

    Construct an istringstream from that string. The text now sits inside the stream as an input source.

  3. 3
    Extract the first value

    The first >> reads 7 and stores it in an int.

  4. 4
    Extract the second value

    The next >> reads 2.25 and stores it in a double.

  5. 5
    Extract the third value

    The final >> reads blue and stores it in a std::string.

Result

The program holds the int 7, the double 2.25, and the string blue, without ever splitting the text by hand.

Tracing the Read Position

Each extraction takes the next piece of text out of the stream, so the stream effectively moves forward as values are read. Before the first >> runs, the next unread piece is 42. After it runs, the next unread piece is 3.5, and so on. The diagram below marks which parts of the text have been pulled out and which remain.

42extracted into a3.5extracted into bhellonext to extract
After the first two extractions, where is the stream's read position, and which pieces have been taken out?

Notice that the pieces already taken out are no longer available to the next >>. The next extraction starts at the first unread piece, which here is hello. This is why the same stream cannot give the program 42 a second time unless the stream is set up again.

str() Versus the Extracted Values

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, rather than as separate values.

What do you think happens?

After the three extractions in the earlier example, what does in.str() return: the full text 42 3.5 hello, or only the text that has not been read yet?

  • The full text 42 3.5 hello

  • Only the unread text, which is empty

Reveal answer
Answer:

The full text 42 3.5 hello

str() returns the whole buffer the stream was built from. Extracting values with >> does not remove that text from what str() returns, so the stream still reports the complete string even though its values have already been read.

cpp
Output
value read: 42
whole text: 42 3.5 hello
Notes on the code
  • a holds the single value extracted by >>
  • in.str() returns the entire string the stream holds, not the extracted value

istringstream and ostringstream Side by Side

The source gives a common use for an ostringstream: formatting something before giving the resulting string to a GUI. The stream collects formatted output, and the finished string is then passed on. The two classes work in opposite directions, so choosing between them depends on whether you are parsing text or building it.

istringstreamText goes in firstProgram takes piecesoutUse: parsing a stringostringstreamProgram writes valuesinFinished string isproducedUse: building astring for a GUI
Which direction does data flow for each stream class, and which one fits parsing text versus building text?
Aspectistringstreamostringstream
Direction of dataText goes in, then values are read outValues go in, then a finished string comes out
Typical jobInterpreting a string the program has receivedFormatting a string before it is handed to a GUI
Retrieving the whole textUse str() on the streamUse str() on the stream
Typical operatorFormatted input such as >>Formatted output such as <<

Choosing the right string stream class

Mistakes With Formatted Input

  • Common mistake

    Using an istringstream to build text for a GUI

    What it looks like

    Reading from an istringstream to produce the label text shown on screen.

    Why it fails

    An istringstream is a source you read from. Building text for output is the job of an ostringstream.

    Do this instead

    Use an ostringstream, write the formatted values into it, and pass the finished string on.

  • Common mistake

    Expecting str() to return only the unread values

    What it looks like

    After extracting 42, expecting in.str() to give 3.5 hello.

    Why it fails

    str() returns the whole text the stream holds, not the portion still to be read.

    Do this instead

    Keep the extracted values in their own variables, and use str() only when you need the complete text.

  • Common mistake

    Assuming the string must be split by a manual loop first

    Why it fails

    The source describes placing the string into an istringstream so the formatted input operations can do that work.

    Do this instead

    Construct the istringstream from the string and extract values with >>.

Parsing a Record From a GUI

EASY

A GUI hands the program the string 19 88.5 ready. Write the steps that place this string into an istringstream and extract an int, a double, and a string. Then state what str() would return after all three extractions.

Hints
  • Begin by constructing an istringstream from the string.
  • Each >> reads the next piece of text into a variable of matching type.
  • Remember that str() returns the whole text, not the values already read.

Key Takeaways

  • An istringstream is a class for reading from a string stream, and it suits programs that need to interpret a string.
  • A string received from a GUI can be placed into an istringstream and read with formatted input operations, avoiding hand-written parsing of the text.
  • Formatted input extracts values one piece at a time, while str() returns the whole text the stream holds.
  • An istringstream is a source you read from, whereas an ostringstream is used to format output into a string before it is passed to a GUI.

Related concepts

More concepts starting with F