helpme
helpme

Reputation: 3

how do you split an array in c++?

Im trying to do a simple string splitting function, but im having a problem returning the split string.

i got the string into strings s1, s2, s3. how do i return {s1,s2,s3}? im using brackets but the compiler is telling me

expected primary-expression before '{' token 
expected `;' before '{' token 
expected `;' before '}' token 

even though there doesnt seem to be any problem. is doing {s1,s2,s3} even allowed?

Upvotes: 0

Views: 225

Answers (4)

Matteo Italia
Matteo Italia

Reputation: 126937

Nope. You have to put your strings in an appropriate container that will be returned by your function; you could use, for example, std::vector<std::string>:

std::vector<std::string> YourFunction(/* ... */)
{
    std::vector<std::string> ret;
    // ...
    ret.push_back(s); // you should call this for each string
    // ...
    return ret;
}

Thanks to RVO this shouldn't be as heavyweight as it may seem.

Upvotes: 1

egrunin
egrunin

Reputation: 25083

You probably want to return type vector<string>. Then in your function create a vector and return it as a value.

Upvotes: 0

GManNickG
GManNickG

Reputation: 504303

You should populate a std::vector and return that.

std::vector<std::string> tokenize(/*...*/)
{
    std::vector<std::string> result;

    // ...
    result.push_back(s); // s: s1 - s3
    // ...

    return result;
}

Note you shouldn't actually have the variables s1, s2, or s3, or you're just limiting the process to three outputs. You should have a loop through the string, pushing results into the vector.

Upvotes: 3

Puppy
Puppy

Reputation: 147036

That's not a valid syntax at all. If you have C++0x, you could return std::make_tuple(s1, s2, s3), or alternatively (and much more sensibly) you could just return a std::vector<std::string>.

Upvotes: 0

Related Questions