0

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() ?

Community
  • 1
  • 1
Kevin217
  • 724
  • 1
  • 10
  • 20
  • 5
    [Cannot reproduce](http://coliru.stacked-crooked.com/a/2acde687043340b1). Do note that every space gets treated as a empty string when you have multiple empty spaces in a row. – NathanOliver Nov 16 '16 at 18:23
  • @NathanOliver It's weird that if I run your code, everything works fine. But once I put those two functions into a header called `helper.h` and `helper.cpp`, it will have the same issue. – Kevin217 Nov 16 '16 at 18:57

0 Answers0