2
main(int argc, char *argv[])
{
if(argc != 3) {
printf("Invalid number of arguments\n");
exit(1);
}}

如果计数与所需的参数数量不匹配,我将直接退出程序

如果参数的数量与计数不匹配,有什么方法可以要求用户重新输入命令行参数?我的意思是不退出程序..

4

1 回答 1

2

尝试:

#include <iostream>
#include <string>
std::string askUser(std::string const& question)
{   
     std::cout << question << "\n";

     std::string result;
     std::getline(std::cin, result);

     return result;
}   
int main(int argc, char* argv[])
{   
    std::string  arg1;
    std::string  arg2;
    std::string  arg3;

    arg1   = (argc > 1) ? std::string(argv[1]) : askUser("Please Enter Arg1");
    arg2   = (argc > 2) ? std::string(argv[2]) : askUser("Please Enter Arg2");
    arg3   = (argc > 3) ? std::string(argv[3]) : askUser("Please Enter Arg3");
 }   
于 2013-01-04T07:04:31.550 回答