Search code examples
cstringargvatoi

storing argv[1] to a char or int in C


So, I'm not sure whether I should try to convert argv[1] to an int or if I can leave it as a char. But I'm having difficulties getting argv to behave the way I want it to.

My terminal input will look like this:

./a.out a

where argv[1] can either be an 'a' or a 'd'.

The Problem: when trying to pass it through an if statement such as:

int main(int argc, char *argv[])
{
  char *letter;
  letter=argv[1];

  printf(" %s  %s ", argv[1], letter); //THIS prints correctly

//However, even when the input IS 'a', it will still print this:

  if(letter != "a" || letter != "d") 
      printf("Input letter not 'a' or 'd'\n");
  else{//More stuff//}    
}

I get all kinds of errors when I attempt to fix it myself. I saw a few threads explaining argv[1][0] and using atoi, but after playing around with it, I could not get it to print out.


Solution

  • There is no sense to compare the value of the pointer argv[1] with the addresses of the first characters of the string literals "a" and "d".

    Just write

    #include <string.h>
    
    //...
    
    if( letter == NULL || ( strcmp( letter, "a" ) != 0  && strcmp( letter, "d" ) != 0 ) ) 
          printf("Input letter not 'a' or 'd'\n");