**Discussion 7** 10/06, 10/08 [(back to course webpage)](./mcs360_fall2020.html) # Stringstreams Suppose you have a string in a .txt file which you want to input to your C++ program as if a user was inputting the string into the console. Stringstreams are useful in this kind of a scenario. ## Basic code + Library: `#include ` + Declaration: `stringstream ss` or `stringstream ss(str)` where `str` is some string object + Methods: * `str()`: return the contents of the stringstream as a string object * `clear()`: clear the stringstream * `operator <<`: append a string to the stringstream * `operator >>`: read a string from the stringstream ## Example: Separating words from a string sentence Let's say we have a string `s` which is the sentence "Welcome to MCS 360." We want to extract each word from this sentence and put them into `std::vector words`. These are the steps we would need to go through: + Remove all punctuations + Put the stripped string into a stringstream + Use the `>>` operator to keep reading words from the stringstream, and adding them into the vector `words`. ~~~~~~cpp #include #include #include #include std::string removePunc(std::string s) { std::vector punc({'.',',','\'','\"','?','!'}); for(int i=0; i < s.length(); i++) { if(std::find(punc.begin(), punc.end(), s[i])!=punc.end()) { s[i] = ' '; } } return s; } int main() { std::string s = "Welcome to MCS 360."; std::string s_new = removePunc(s); std::cout << "\n ** String after removing punctuations: " << s_new << std::endl; std::vector words; std::string temp; // Now define the stringstream object std::stringstream ss(s_new); // Read words from ss and push them into words while(ss >> temp) { words.push_back(temp); } // Output the vector words std::cout << "Extracted words:\n"; for(int i = 0; i < words.size(); i++) std::cout << words[i] << std::endl; return 0; } ~~~~~~ ## Exercise Given a string containing space-separated integers, extract the numbers in the string and put them into a `std::vector`.