2

I have an input getline: man,meal,moon;fat,food,feel;cat,coat,cook;love,leg,lunch

And I want to split this into an array when it sees a ;, it can store all values before the ; in an array.

For example:

array[0]=man,meal,moon

array[1]=fat,food,feel

And so on...

How can I do it? I tried many times but I failed! Can anyone help?

Thanks in advance.

Therese
  • 39
  • 1
  • 2
  • 7
  • With arrays it would be difficult, I would suggest looking up with Vectors and Stream. http://stackoverflow.com/questions/236129/split-a-string-in-c – Kishore Bandi May 04 '16 at 11:39
  • If you know the number of elements in the array before hand then you can use an `array` or `std::array`. But if you only know the size at runtime you should be using `std::vector` (it is a resizable array). – Martin York May 04 '16 at 11:47
  • I know it's difficult by arrays, but i have a great project and i need arrays to quick doing the next steps – Therese May 04 '16 at 11:48
  • 1
    Why do you think vector is slow? – Martin York May 04 '16 at 11:51
  • i didn't try to use vector before, do you think it will be useful? – Therese May 04 '16 at 11:57
  • The `std::vector` is probably the most used container in C++. It is as fast as the built in array with the additional benefit that it is resizeable. You see raw arrays used very seldomly in C++. – Martin York May 04 '16 at 12:14

1 Answers1

1

You can use std::stringstream and std::getline.

I also suggest that you use std::vector as it's resizeable.

In the example below, we get input line and store it into a std::string, then we create a std::stringstream to hold that data. And you can use std::getline with ; as delimiter to store the string data between the semicolon into the variable word as seen below, each "word" which is pushed back into a vector:

int main()
{
    string line;
    string word;
    getline(cin, line);
    stringstream ss(line);

    vector<string> vec;
    while (getline(ss, word, ';')) {
        vec.emplace_back(word);
    }

    for (auto i : vec) // Use regular for loop if you can't use c++11/14
        cout << i << '\n';

Alternatively, if you can't use std::vector:

string arr[256];
int count = 0;
while (getline(ss, word, ';') && count < 256) {
    arr[count++] = word;
}

Live demo

Outputs:

man,meal,moon
fat,food,feel
cat,coat,cook
love,leg,lunch
Andreas DM
  • 10,685
  • 6
  • 35
  • 62
  • wow, it works! thanks so much. And if i want to take "man,fat,cat,love" in one another array and also "meal,food,coat,leg" "moon,cook,lunch" ... Can i use the same code with a "for loop" for array? – Therese May 04 '16 at 12:12