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

Print using command line arguments

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

Im trying make a program print a specific output using a enviroment variable in the command line, but the program seems to be stuck on my first input.

Here's my code

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

My problem is that the program either only prints "Value set to key" or "Value set to last name". How can I use the pointer in Print_data to check what command is entered in the command line?

Output: enter image description here

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

if(select, "k") is almost certainly not doing what you want, but it is not entirely clear what it is that you want. That expression is equivalent to if(1), which is why you get the behavior you see. Perhaps you intend:

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

which would be better written:

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