How does this code work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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));

11th Oct 2020, 9:17 PM
ItzNekS
ItzNekS - avatar
2 Answers
+ 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.
11th Oct 2020, 9:36 PM
Shadow
Shadow - avatar
+ 1
thank you for explaining Shadow
12th Oct 2020, 6:14 AM
ItzNekS
ItzNekS - avatar