Search code examples
c++stringvectortokenize

Parsing vector<string> into a string


I'm trying to tokenize a string. The strings I'm working on have the following format:

name,city,major,color,hobbies,age. 

I'm using the code below to do that. And temp is a string.

    cin>>command;
    vector <string> tokens;
    stringstream check(command);
    string middle;
    while(getline(check, intermediate, ','))
    {
        tokens.push_back(intermidiate);
    }
    for(int i = 0; i<tokens.size(); i++)
    {
        cout << tokens[i] <<endl;

    }
    temp = tokens[1];
    cout<<temp; 

And I'm trying to parse the vector of string into just a string, but my program crashes when I tried to do that...

Is there a way to parse it into just a string or should I try something else entirely?


Solution

  • You don't check if you access a valid element in the vector. So it's probable that you go out of bounds. To prevent this replace the end of your code with:

    cout << tokens.size() << " elements:"<<endl;
    if (tokens.size()>1)
        temp = tokens[1];
    else temp = "Second element not found";
    cout<<temp; 
    

    Also, the way you read command will stop reading at the first space separator:

    cin>>command;    //entering "hello world" would cause command to be "hello"
    

    In order to be sure that your string is not shortened in this unexpected fashion, you could consider using getline() instead:

    getline (cin,command);
    

    Demo

    Note: the terme parse is misleading. I understood that you want to extract just one specific value of the array. But if you want to concatenate several vector elements into a single string, you need to do a little more.

    string tmp; 
    for (auto const& x:tokens)
        tmp += x+" ";
    cout << tmp<<endl;