0
How does this code work?
please explain how this piece of code works: std::istringstream iss{phrase}; std::vector<std::string> words; std::string word; while (iss >> word) words.push_back(std::move(word));
2 ответов
+ 3
First, you set up a std::istringstream instance, which maps the "phrase" string.
https://en.cppreference.com/w/cpp/io/basic_istringstream
Afterwards, you declare a vector and a single string, which is going to act as a temporary storage.
The while loop is probably the most interesting part. The std::string class overloads the input operator >> for stream-based operations:
https://en.cppreference.com/w/cpp/string/basic_string/operator_ltltgtgt
The operator will skip preceding whitespace and then store subsequent characters in the string ("word" in this case) by extracting them from the stream. It stops extracting characters once it encounters a whitespace character. The resulting string will contain no whitespace and is moved into the container. At this point, the loop starts again by skipping the preceding whitespace characters in the stream. This goes on until a newline character is encountered, which will set an internal flag that the end of the string has been reached, and the loop terminates.
+ 1
thank you for explaining Shadow