2016-11-08 122 views
-2

任何人都可以解释为什么getMessage()函数中的cout没有读出。我的目标是将argv [i]作为先前存储的值传递。将一个argv作为一个存储的字符串传递给函数

这是我的代码到目前为止。我对命令行参数很陌生,任何帮助都会很棒。

#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; 

} 
+4

你不调用'getMessage'。 –

+0

当你运行它时你给它命令行参数吗? – Galik

+0

@Galik这不重要。 –

回答

1

它的确行得通,因为你根本没有打电话给getMessage()。它应该更像这样:

#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; 
} 
相关问题