Courtney Greer Courtney Greer - 1 month ago 7
C++ Question

passing an argv to a function as a stored string

Can anyone explain why the cout in the getMessage() function doesn't read out. My goal is to pass an argv[i] as a previously stored value.

Here is a my code so far. I'm new to command line args any help would be great.

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

void getMessage(string action);

int main(int argc, char* argv[])
{

string action = argv[1];
cout << action << endl;
}

void getMessage(string action)
{
cout << "I said " << action << endl;

}

Answer

It does's work because you are not actually calling getMessage() at all. It should more like this instead:

#include <iostream>
#include <string> 

using namespace std;

void getMessage(const string &action);

int main(int argc, char* argv[])
{
    if (argc > 1)
    {
        string action = argv[1];
        getMessage(action);
    }
    else
        cout << "no action specified" << endl;

    return 0;
}

void getMessage(const string &action)
{
    cout << "I said " << action << endl;
}