2016-11-08 31 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; 
} 
相關問題