2016-11-23 63 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