Therese
Therese

Reputation: 49

How can I split a getline() into array in c++

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.

Upvotes: 2

Views: 9027

Answers (1)

Andreas DM
Andreas DM

Reputation: 10998

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

Upvotes: 1

Related Questions