I'm working with a command line arguments for the first time and I need to convert one of the string arguments to a character for testing. I tried testing it as a string and it wasn't working. In the program the user needs to enter an e or E or d or D (sample input at top of code). I haven't done much with conversions in C either so any help would be great. Thanks.
Input is: ./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;
}
}
argv is of type char **, such that char c = argv[4] assigns a pointer to a character value; this should actually give a warning / error.
If you want to assign the first letter of the 4th argument, write char c = *(argv[4]) or char c = argv[4][0]
And dont't forget to check if you have enough arguments provided before accessing argv[4], i.e.
if (argc > 4) {
char c = *(argv[4]);
...
Note further that if(letter != 'd' || letter != 'D' || letter != 'e' || letter != 'E') rarely makes sense since for any letter condition letter != 'd' || letter != 'D' is always true, because letter cannot be both d and D at the same time. you probably meant &&...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With