-1

I am writing program in which the first argument must be char type and the second one an int. I already wrote the code for the int type but can't make it for the char. I have searched everywhere, but I cannot find an answer to my problem, here is the code:

int main(int argc, char *argv[]){
    if(argc != 3){
         puts("Error: Invalid number of arguments\n");
         exit(0);
    }
    if(argv[1] ??){
         puts("Error: First argument not a char type\n");
         exit(0);
    }
}
cela
  • 2,352
  • 3
  • 21
  • 43
Rui Inacio
  • 25
  • 5
  • 2
    When you receive the arguments from the command line via `char *argv[]`, each element of the `argv` array is the pointer to a standard C string, terminated as C strings are with a `0` byte. They are string representations of the command line arguments. If one of them represents an integer, you have to apply a string-to-integer function and check the results. There's nothing more special about `char *argv[]` which is why you cannot find anything after all the searching. However, you can Google "process command line arguments in C" and find useful information. – lurker Jun 08 '18 at 01:12
  • Possible duplicate of [C - reading command line parameters](https://stackoverflow.com/questions/5157337/c-reading-command-line-parameters) – lurker Jun 08 '18 at 01:30
  • 2
    What exactly do you mean with "char type"? All arguments are basically char type, as they are strings. Do you mean "not a number"? Or "letters from A to Z"? You could use `isalpha()` or `!isdigit()` on the first character of your string. – Gerhardh Jun 08 '18 at 07:23
  • regarding this kind of statement: `puts("Error: Invalid number of arguments\n");` Error messages should be output to `stderr`, however, `puts()` outputs to `stdout`. For the checks of the parameter list, suggest using: `fprintf( stderr, "...\n";) Also, when the incorrect number of parameters have been passed to `main()` it is the normal practice to output a `USAGE` message showing the user how it should be done. Similar to: `fprintf( stderr, "USAGE: %s \n", argv[0] );`, – user3629249 Jun 09 '18 at 03:56

1 Answers1

1

The reason is explained above by lurker. If you want to validate the first argument is a char from the command line, isascii might be what you are looking for. More validation on argv[1] should be done to avoid Segmentation fault.

    if (argv[1][1]!='\0'||!isascii(argv[1][0])) {
        puts("Error: First argument not a char type\n");
        exit(0);
}

" isascii() checks whether c is a 7-bit unsigned char value that fits into the ASCII character set." and don't forget to #include <ctype.h>

runwuf
  • 1,701
  • 1
  • 8
  • 15