0
line = "hello 2021"
istringstream split_string(line);

was a useful code to get the values from a string, i.e.

split_string>>str>>temp_double;

However, suppose that the value of line was changed, i.e.

line="hello world"

,and one wanted to write the following code with the updated value of line.

split_string>>str1>>str2;

How to update split_string so that it streamed the updated value of line?

  • Does this answer your question? [how to reuse stringstream](https://stackoverflow.com/questions/12112259/how-to-reuse-stringstream) – Justin Mar 04 '21 at 04:04

1 Answers1

1

In the C++20 standard std::istringstream now has an str() method that allows replacing the contents of its internal buffer. This functionality is not available in C++17 or earlier.

Before C++20 the closest alternative would be to use std::stringstream instead of std::istringstream and use << to put stuff into the string stream that can be read back out.

CORRECTION: it possible to use str() to set the contents of std::istringstream prior to C++20, so this is the simplest solution.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • 3
    An `istringstream::str()` overload that allows replacing the buffer has been around for a long time ([demo](https://ideone.com/H3QuaN)). What was added in C++20 are just new overloads for handling custom allocators, and rvalue references. – Remy Lebeau Mar 04 '21 at 05:16