comm2231
comm2231

Reputation: 13

C++ Cannot print vector of string element

Why I can't print third element of my vector ? I'm need a words that will be divided to vector and after that, they will be printed. But my third element of vector isn't showing in the terminal.

#include <iostream>
#include <vector>
using namespace std;

void divideTextCommand(string txt, vector<string> cmd)
{

    string word = "";
    for (auto x : txt)
        {
            if (x == ' ')
            {
                cmd.push_back(word);
                word = "";
            }
            else
            {
                word = word + x;
            }
        }
        cmd.push_back(word);

}


int main()
{
    cout << "Command:" << endl;
    string textCommand; getline(cin, textCommand);
    vector<string> command;
    cout << " " << endl;
    divideTextCommand(textCommand, command);

    cout << command[2];

    return 0;
}

In my terminal program looks like this

bob@msi:~/Desktop/project$ ./output
Command:
barry jack fred john
 
Segmentation fault (core dumped)

Upvotes: 0

Views: 212

Answers (3)

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

You are currently not providing a reference to command:

void divideTextCommand(string txt, vector<string> cmd)
                                    // ^ this is a copy, original is not edited

I would suggest you simply return your command:

std::vector<std::string> divideTextCommand(std::string txt) {
    std::vector<std::string> cmd
    ...
    return cmd; // Thanks to RVO, this is no more expensive and is much clearer.

Upvotes: 1

catnip
catnip

Reputation: 25388

You need to pass cmd by reference:

void divideTextCommand(string txt, vector<string> &cmd)
//                                                ^

As it is, command in main remains empty so accessing element [2] is UB.

But I prefer Fantastic Mr Fox's suggestion - split your words into a locally declared array in divideTextCommand and then return that as the function result. It's more natural and carries no performance penalty.

Upvotes: 1

user15202364
user15202364

Reputation:

In your code, in:

void divideTextCommand(string txt, vector<string> cmd)

the vector<string> cmd inside the function now will only be a copy of the inputed version, and will be stored in a completely different memory location. Therefore, any changes made to cmd inside the function will not reflect back to the original variable. This is called pass by value.

To solve it, you simply use pass by reference, by adding a & before your param:

void divideTextCommand(string txt, vector<string> &cmd)

By doing this we're refering to the address of cmd, and changes will be made to both versions.

Result (with your code, adding the &):

Command:
fred george alex john

alex

More info :

Upvotes: 0

Related Questions