HackerRank C++ StringStream




stringstream is a stream class to operate on strings. It basically implements input/output operations on memory (string) based streams. stringstream can be helpful in different type of parsing. The following operators/functions are commonly used here

Operator >> Extracts formatted data.
Operator << Inserts formatted data.
Method str() Gets the contents of underlying string device object.
Method str(string) Sets the contents of underlying string device object.
Its header file is sstream.

One common use of this class is to parse comma-separated integers from a string (e.g., "23,4,56").

stringstream ss("23,4,56");
char ch;
int a, b, c;
ss >> a >> ch >> b >> ch >> c; // a = 23, b = 4, c = 56
You have to complete the function vector parseInts(string str). str will be a string consisting of comma-separated integers, and you have to return a vector of int representing the integers.



  1. #include <sstream>
  2. #include <vector>
  3. #include <iostream>
  4. using namespace std;
  5. vector<int> parseInts(string str)
  6. {
  7. stringstream ss(str);
  8. vector<int> out;
  9. char ch;
  10. int temp;
  11. while(ss >> temp)
  12. {
  13. out.push_back(temp);
  14. ss >> ch;
  15. }
  16. return out;
  17. }
  18. int main()
  19. {
  20. string str;
  21. cin >> str;
  22. vector<int> integers = parseInts(str);
  23. for(int i = 0; i < integers.size(); i++)
  24. {
  25. cout << integers[i] << "\n";
  26. }
  27. return 0;
  28. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube