【问题标题】:How to check program start parameters from Windows Console?如何从 Windows 控制台检查程序启动参数?
【发布时间】:2016-01-25 10:02:25
【问题描述】:

在我的程序开始时,它应该从控制台获取输入文件的路径和输出文件的路径。 但是,如果用户提供了不需要的参数数量或错误的参数(例如,带有空格,或没有“.txt”),它应该给用户第二次机会在不退出程序的情况下输入这些参数。有可能吗?

int main(int argc, char* argv[])
{ //and here should be something to check if the user entered parameters correctly 
//(number and if they look like a path) and give a user another try if this is wrong 
//(so that user enter them from console again)

string path_open(argv[1]);
  strin path_out(argv[2]);

【问题讨论】:

  • 有可能吗? 是的,这当然有可能。同样在您的示例代码中,您应该在使用 argv[1] ... 之前检查 argc
  • 是的,可以再次询问用户。但你为什么要考虑这个?如果用户输入垃圾,写入错误信息并退出。编写代码没有令人信服的理由,这给了用户第二次机会。如果他们需要第二次机会,让他们再次调用您的程序。

标签: c++ parameters argv argc


【解决方案1】:

是的,这是可能的,但是……很奇怪。如果你要让你的程序要求输入,为什么不把 that 放在一个循环中,直到你得到正确的输入?最终,我会做一个或另一个:

  1. 获取命令行输入(并且,正如@IInspectable 在 cmets 中所建议的,如果它无效,则退出程序);或
  2. 让程序递归地请求输入,直到用户提供有效输入。

命令行输入

int main(int argc, char* argv[])
{
    // sanity check to see if the right amount of arguments were provided:
    if (argc < 3)
        return 1;
    // process arguments:
    if (!path_open(argv[1]))
        return 1;
    if (!path_out(argv[2]))
        return 1;
}

bool path_open(const std::string& path)
{
    // verify path is correct...
}

程序要求输入:

int main()
{
    std::string inputPath, outputPath;
    do
    {
        std::cout << "Insert input path: ";
        std::getline(std::cin, inputPath);
        std::cout << std::endl;
        std::cout << "Insert output path ";
        std::getline(std::cin, outputPath);
    } while (!(path_open(inputPath) && path_out(outputPath)));
}

当然,如果输入的输入路径有效但输出路径无效,您会单独验证输入,但您明白了要点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多