Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::stringstream — reading and writing text in memory

std::stringstream from <sstream> formats values as text and reads values from text held in memory. It combines the << and >> operators with a string buffer and stream error state.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <sstream>
std::stringstream stream;
stream << value;
stream >> variable;
std::string text = stream.str();

std::stringstream from <sstream> is an alias for std::basic_stringstream<char>. It holds text in memory and supports both reading and writing by default. std::istringstream is for reading, whereas std::ostringstream is for writing.

The << operator formats values into the buffer, and >> reads values into variables. Formatted extraction skips leading whitespace by default; extraction into std::string stops before the next whitespace character. Number formatting depends on the stream's locale; the example sets std::locale::classic().

For a named stream, stream.str() returns a copy of the text, including portions already read. The reading and writing positions are separate: writing does not advance the reading position. However, do not assume that every subsequent write appends; that depends on the writing position and opening mode.

Check success with if (stream >> value). A failed conversion can set failbit, and reaching the end of the input can set eofbit. To reuse the stream with new text, call stream.clear(); stream.str("new text");. clear() resets state flags but neither removes text nor rewinds the stream; str(...) replaces the text but does not reset error flags.

Examples

#include <iostream>
#include <locale>
#include <sstream>
#include <string>

int main() {
    std::stringstream stream;
    stream.imbue(std::locale::classic());
    stream << "Ada " << 42;

    std::string name;
    int score = 0;
    if (stream >> name >> score) {
        std::cout << name << '\n';
        std::cout << stream.str() << '\n';
    } else {
        return 1;
    }
}

Result

Ada
Ada 42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources