use getline and while loop to split a string

As Benjamin points out, you answered this question yourself in its title.

#include <sstream>
#include <vector>
#include <string>

int main() {
   // inputs
   std::string str("abc:def");
   char split_char=":";

   // work
   std::istringstream split(str);
   std::vector<std::string> tokens;
   for (std::string each; std::getline(split, each, split_char); tokens.push_back(each));

   // now use `tokens`
}

Note that your tokens will still have the trailing/leading <space> characters. You may want to strip them off.

Leave a Comment