0

I have a std::string that contains comma separated values, i need to store those values in some suitable container e.g. array, vector or some other container. Is there any built in function through which i could do this? Or i need to write custom code for this?

Jame
  • 21,150
  • 37
  • 80
  • 107

4 Answers4

3

If you're willing and able to use the Boost libraries, Boost Tokenizer would work really well for this task.

That would look like:

std::string str = "some,comma,separated,words";
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep(",");
tokenizer tokens(str, sep);
std::vector<std::string> vec(tokens.begin(), tokens.end());
jwismar
  • 12,164
  • 3
  • 32
  • 44
2

You basically need to tokenize the string using , as the delimiter. This earlier Stackoverflow thread shall help you with it.

Here is another relevant post.

Community
  • 1
  • 1
Ozair Kafray
  • 13,351
  • 8
  • 59
  • 84
0

I don't think there is any available in the standard library. I would approach like -

  1. Tokenize the string based on , delimeter using strtok.
  2. Convert it to integer using atoi function.
  3. push_back the value to the vector.

If you are comfortable with boost library, check this thread.

Community
  • 1
  • 1
Mahesh
  • 34,573
  • 20
  • 89
  • 115
0

Using AXE parser generator you can easily parse your csv string, e.g.

std::string input = "aaa,bbb,ccc,ddd";
std::vector<std::string> v; // your strings get here
auto value = *(r_any() - ',') >> r_push_back(v); // rule for single value
auto csv = *(value & ',') & value & r_end(); // rule for csv string
csv(input.begin(), input.end());

Disclaimer: I didn't test the code above, it might have some superficial errors.

Gene Bushuyev
  • 5,512
  • 20
  • 19