Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::istringstream — reading values from text

std::istringstream reads values from in-memory text using operator >>. It follows the same formatting rules and error-state conventions as other input streams, without opening a file.

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

Syntax

#include <sstream>
std::istringstream input{"42 7"};
int value{};
while (input >> value) {
    // Use value.
}

std::istringstream, declared in <sstream>, is an alias for std::basic_istringstream<char>. It provides stream input from an in-memory text buffer. It is useful for splitting a line into words and numbers; unlike std::ostringstream, it reads text rather than building output text.

Construct the stream from text, then extract values with >>. By default, formatted extraction skips leading whitespace, and extraction into std::string stops before the next whitespace character. Number interpretation depends on the stream's locale. The example explicitly selects std::locale::classic() and prints Ada 42 followed by a newline.

Test the extraction result: if (input >> value) or while (input >> value). The condition is false when failbit or badbit is set. eofbit alone does not mean extraction failed: the final value can be read successfully while the end of input is detected. Do not control the loop with while (!input.eof()). Successful numeric extraction also does not prove that all text was consumed: after reading a number from "12x", the x remains in the buffer.

To reuse the stream after failure or end of input, call input.clear(); input.str("10 20");. clear() resets the state flags but does not remove text; str(...) replaces the text but does not reset those flags. This entry uses features available in C++23; the cited working draft is an evolving document, not a frozen C++23 specification.

Examples

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

int main() {
    std::istringstream input{"Ada 17 25"};
    input.imbue(std::locale::classic());

    std::string name;
    int first{};
    int second{};
    if (!(input >> name >> first >> second)) {
        std::cout << "invalid input\n";
        return 1;
    }

    std::cout << name << ' ' << first + second << '\n';
}

Result

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