【发布时间】:2016-11-23 18:08:10
【问题描述】:
我是 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...
}
在main方法中为:
int main(int argc, char** argv) {
iFilename[] = argv[1];
oFilename[] = argv[2];
file_process::process(iFilename[], oFilename[]);
}
之前我硬编码文件名来测试我的程序,在 main 方法中没有参数,并将源文件中的变量(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];
有效。 我
【问题讨论】:
-
在 C++ 中,您将执行与 C# 中几乎相同的操作,即:
std::string iFilename = argv[1],然后将变量作为 C++ 字符串传递给函数或使用 std:: 作为 C 字符串传递字符串::c_str()。 -
您无法编译它,因为...?
-
file_process::process需要一种类型的参数,而不仅仅是一个名称。不要忘记 arg[0] 是 exe 名称。不要忘记const需要的地方。或使用std::string
标签: c++ command-line-arguments