2013-10-11 23 views
0

假设我想通过命令(使用argc和argv)打开该程序。你得到你的程序名称,打开程序。它给你的.exe。然后,一旦你的program.exe运行,添加另一个参数,如(program.exe打开),它应该在你的程序中打开一些东西。打开通过命令参数执行某些操作的函数

if (argc >= 5){ 
    if (int(argv[1]) == 1){ 
     function1(); 
     function2(); 
     function3(); 

    } 

} 

基本上在这种情况下,如果用户输入program.exe 1,(1是本例中的开头),它应该执行以下功能。为什么这在逻辑上不正确? (因为其中没有显示)

+0

一开始,'的Program.exe 1'不会导致'ARGC> = 5' ... –

回答

0

因为int(argv[1])"1"不转换为int1。试试这个:

if (argv[1][0] == '1') { 
+0

当然,如果的argv [1]正好是 “10” 这可能没有做什么要求 – doctorlove

2

你需要的是这样的:

if (argc >= 2){ // the argc is count of supplied argument 
       // including executable name 
    if ((argv[1][0]-'0') == 1){ 
     //argv[1] will be "1" 
     //so take first character using argv[1][0]--> gives '1'-->49 
     //substract ASCII value of 0 i.e. 48 
     //Note: - This will only work for 0-9 as supplied argument 
     function1(); 
     function2(); 
     function3(); 

    } 

} 
+0

事实上,但不是非常可扩展的(从输入值大于9的时候这会破坏)... –

1

你的argv转换[1]为int不起作用。你可以使用atoi()

if (argc >= 2){ 
    if (atoi(argv[1]) == 1){ 
     function1(); 
     function2(); 
     function3(); 
    } 
} 
+0

这适用于输出任何cout <<。但是,尝试使用这些功能时,它什么也不显示。我有一个函数打开一个文件,另一个打开另一个文件,然后在这些函数的结尾处我有一个文本。在调用if语句中的函数时,没有文本存在 –

+0

我编辑了我的答案,将argc与2进行比较。如果您正在调用程序:'program.exe 1',那么argc将是2。 –

相关问题