2016-01-25 46 views
-1

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

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

***是否有可能?***是的,这当然是可以的。同样在你的示例代码中,你应该在使用argv [1]之前检查argc ... – drescherjm

+1

是的,可以再次询问用户。但为什么你会考虑这个?如果用户输入垃圾,请写入错误消息并退出。编写代码没有令人信服的理由,为用户提供了第二次机会。如果他们需要第二次机会,让他们再次调用您的程序。 – IInspectable

回答

1

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

  1. 获取命令行输入(和,@IInspectable建议在评论中,如果它是无效的,退出程序);或
  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))); 
} 

当然你会验证输入分开的情况下,他们进入了一个有效的输入路径但无效的输出路径,但您获得了要点。

相关问题