I copy the code from this answer Split a string in C++?
#include <string>
#include <sstream>
#include <vector>
void split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss;
ss.str(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
I also add the code to check if item.empty()
Test code --
#include <xxx>
using namespace std;
string str = "0x0 0";
vector<string> result = split (str, ' ');
The result should be --
["0x0", "0"]
But It doesn't split the string, and the result is --
["0x0 0"]
However, It works fine when --
str = "a b c d ";
Is there something that I miss when using std::getline()
?