Convert command line argument to char

I am working with command line arguments for the first time, and I need to convert one of the string arguments to a character for testing. I tried checking it as a string and it did not work. In the program, the user needs to enter e or E or d or D (sample entry at the top of the code). I haven’t done much with C conversions so that any help is great. Thank.

Input: ./filename 4 1 7 e

int main(int argc, char *argv[])
{
   char letter = argv[4];
   if(argc != 5)
   {
      printf("Error - wrong number of inputs args\n");
      return -1;
   }

   if(letter != 'd' || letter != 'D' || letter != 'e' || letter != 'E')
   {
      printf("Error - E or D not entered\n");
      return -1;
   }
}
+4
source share
4 answers

A string is just an array of characters ending in zero. So, refer to the first character in the array:

char letter = argv[4][0];

It is also if(letter != 'd' || letter != 'D' || letter != 'e' || letter != 'E')always true, because there lettercannot be both d and D. At the same time, you probably meantif(letter != 'd' && letter != 'D' && letter != 'e' && letter != 'E')

+7
source

argv char **, char c = argv[4] ; /.

4- , char c = *(argv[4]) char c = argv[4][0]

, , argv[4], ..

if (argc > 4) {
  char c = *(argv[4]);
  ...

, if(letter != 'd' || letter != 'D' || letter != 'e' || letter != 'E') , letter letter != 'd' || letter != 'D' , letter d, d. , , &&...

+6

:

if(letter != 'd' || letter != 'D' || letter != 'e' || letter != 'E')

true. , && ||.

+4

"C", , , , argv. argv char **argv, char *argv[], char argv[][]. \0, C.

, , . (@Josh )

if(letter != 'd' || letter != 'D' || letter != 'e' || letter != 'E')

:

if(letter != 'd' && letter != 'D' && letter != 'e' && letter != 'E')

: , d e,

char letter = argv[4]; 

char letter = argv[4][0];

. , debug, "d", "d". , , , :

, argv[4] debug. , , .

if (argv[4][1] != '\0') {
   printf ("5th argument is incomatible\n");
   return -1;
}

, "\ 0", , argv [4] "\ 0".

, .

char letter = argv[4];
if(argc != 5)
{
   printf("Error - wrong number of inputs args\n");
   return -1;
}

/* more code */

segfautl, :). , segfautl, :

if(argc != 5)
{
   printf("Error - wrong number of inputs args\n");
   return -1;
}

char letter = argv[4][0];

/* more code */
+2

Source: https://habr.com/ru/post/1695781/


All Articles