【问题标题】:parsing input and output filename as argument from command line从命令行解析输入和输出文件名作为参数
【发布时间】: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


【解决方案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...
}

【讨论】:

  • 我按照你说的做了但是当我将我的 file_process::process 编辑为 void file_process::process(const std::char& iFilename[], const std::string& oFilename[]);编译器在上面的行中将错误显示为“错误:预期的‘)’”,尽管我看不出需要这个结束括号。上一行中的另一个错误是“预期的初始化程序”我将 iFilename 和 oFilename 初始化为全局 const 为: const char iFilename[100]; const char oFilename[100];
  • 要么选择 C ​​字符串,要么选择你不应该混合的 C++ 字符串,这很奇怪。它不是 std::string[] 是 std::string 的数组...
  • 感谢您指出这是一个错字。我现在修复了代码,您关于 std::string 数组的第二点确实很有帮助。现在我在运行时遇到问题,说明“int main(int, char**): Assertion 'argc>=3' failed.”
  • 断言是为了确保你记得实际提供命令行参数,如果你不这样做,它会断言。
  • 我现在项目中还有一个问题。我正在使用 netbeans,并且没有在项目属性中添加参数。现在项目正在编译,但在运行时它指出 /bin/sh: 1: Syntax error: Unterminated quoted string I googled 但找不到具体答案。知道是什么问题吗?
猜你喜欢
  • 2010-09-16
  • 1970-01-01
  • 2021-01-18
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
相关资源
最近更新 更多