如何从Windows控制台检查程序启动参数?

时间:2016-01-25 00:11:44

标签: c++ parameters argv argc

在我的程序开始时,它应该从控制台获取输入文件的路径和输出文件的路径。 但是如果用户给出不需要的参数数量或错误的参数(例如,带空格或没有“.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]);

1 个答案:

答案 0 :(得分:1)

是的,可能,但......很奇怪。如果你要让你的程序要求输入,为什么不把那个放在一个循环中直到你得到适当的输入?最终,我要做其中一个:

  1. 获取命令行输入(并且,如评论中的@IInspectable建议,如果它无效,退出程序); OR
  2. 让程序递归地询问输入,直到用户提供有效输入。
  3. 从命令行输入

    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)));
    }
    

    当然,如果他们输入的是有效的输入路径但是输出路径无效,你会单独验证输入,但是你得到了要点。