Warm tip: This article is reproduced from serverfault.com, please click

c-使用命令行参数打印

(c - Print using command line arguments)

发布于 2020-11-30 09:25:18

我想在命令行中使用环境变量使程序打印特定的输出,但是该程序似乎卡在了我的第一个输入上。

这是我的代码

#include <stdio.h>
#include <stdlib.h>



void print_data(char*select);

int main (int argc, char * argv[]){

int ret;
char *ch = NULL;


   if( argc == 2)
   {
      ch = argv[1];
   }
   else
   {
      ch = getenv("V1");
   }

   void print_data(ch);

   return 0;
}
void print_data(char* select){

      if(select, "k")
      {
          printf("Value set to key\n");
      }
      else if(select, "l")
      {
         printf("Value set to last name\n");
      }
      else if (select, " ")
      {
         printf("Value set to %s\n", select);
      }
   }

我的问题是该程序只打印“设置为键的值”或“设置为姓氏的值”。如何使用Print_data中的指针检查在命令行中输入了什么命令?

输出: 在此处输入图片说明

Questioner
B0ris
Viewed
0
William Pursell 2020-11-30 17:38:56

if(select, "k")几乎可以肯定,它并没有做你想要的事情,但是还不清楚你想要的是什么。该表达式等效于if(1),这就是为什么你得到看到的行为的原因。也许你打算:

if( select[0] == 'k' ) ...
else if( select[0] == 'l' ) ...
else if( select[0] == ' ' ) ...

最好写成这样:

switch( select[0] ) {
case 'k': ...;
...