ShoutOutAndCalculate
ShoutOutAndCalculate

Reputation: 583

istringstream split_string(line) how to update the split_string while changing line without using while loop?

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?

Upvotes: 0

Views: 62

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118435

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.

Upvotes: 1

Related Questions