2016-11-23 123 views
1

我是新的與c + +和項目中我需要使用命令行參數。 我讀到的命令行參數即包括解析輸入和輸出文件名作爲參數從命令行

int main(int argc, char** argv) 
{ 
} 

,但我說出我的名源文件中的問題。

我聲明瞭源文件(file_process.cpp)在我的輸入和輸出的文件名作爲

const char iFilename[] ; 
const char oFilename[] ; 

中定義的功能(其使用輸入文件 - iFilename並處理在oFilename的輸出)作爲

void file_process::process(iFilename[], oFilename[]) 
{ 
body... 
} 

,並在主方法爲:

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

    iFilename[] = argv[1]; 
    oFilename[] = argv[2]; 
    file_process::process(iFilename[], oFilename[]); 

} 

較早我硬編碼文件名來測試我的程序不帶參數的主要方法和聲明的源文件(file_process.cpp)在變量爲:

const char iFilename[] = "input_file.pdf"; 
const char oFilename[] = "output_file.txt"; 

及其工作正常,但當我試圖通過命令行接受的參數如上所述,我無法編譯它。

這是在c + +做的正確方法嗎?我與C#工作,只是在源文件中聲明像:

string iFilename = args[0]; 
string oFilename = args[1]; 

的作品。 我

+1

在C++中,你會做幾乎一樣C#,那就是:'STD :: string iFilename = argv [1]',然後將該變量作爲C++字符串傳遞給函數,或者使用std :: string :: c_str()將其作爲C字符串傳遞。 – Jonas

+0

你無法編譯它,因爲...? –

+0

'file_process :: process'將需要一個參數類型,而不僅僅是一個名稱。別忘了arg [0]是exe的名字。在需要的地方不要忘記'const'。或者使用'std :: string' – doctorlove

回答

1

下面是做到這一點的一種方法:

int main(int argc, char** argv) 
{ 
    assert(argc >= 3); 
    const std::string iFilename = argv[1]; 
    const std::string oFilename = argv[2]; 
    file_process::process(iFilename, oFilename); 
} 

file_process::process可能是:

void file_process::process(const std::string& iFilename, const std::string& oFilename) 
{ 
    body... 
} 
+0

我照你說的做了 但是當我編輯我的file_process ::進程爲 void file_process :: process(const std :: char&iFilename [],const std :: string&oFilename []); 編譯器在上面一行中顯示錯誤爲「error:expected」)'「,儘管我看不到任何需要關閉這個palenthesis。 上述行中的另一個錯誤是「期望初始值設定項」 我將iFilename和oFilename初始化爲全局常量,如下所示: const char iFilename [100]; const char oFilename [100]; – Saurabh

+0

要麼去C字符串或C++ - 你不應該混合的字符串,這只是奇怪的。它不是std :: string [],它是一個std :: string數組... – Jonas

+0

謝謝你指出這是一個錯字。 我現在修復了代碼,關於std :: string數組的第二點確實有幫助。 現在我在運行時遇到問題:「int main(int,char **):Assertion'argc> = 3'失敗。「 – Saurabh