I searched quite a while to find the answer, but I could only find a solution for C++ that didn't seem to work for C. I'm trying to convert argument of const char * to char to use in my switch statement. I tried various things like strdup(), but was unsuccessful.
#include
int main(int argc, const char *argv[]) {
char argOne = argv[1];
char argTwo = argv[2];
switch(argOne) {
case '1234' :
printf("1234!\n" );
break;
default :
printf("Invalid\n" );
}
}
While compilation:
warning: incompatible pointer to integer conversion initializing 'char' with an expression of type 'const char *' [-Wint-conversion]
char argOne = argv[1];
^ ~~~~~~~
warning: overflow converting case value to switch condition type (825373492 to 52) [-Wswitch]
case '1234' :
^
Answer
In your code,
Point 1:
char argOne = argv[1];is very wrong. You cannot put a
const char *(pointer) to acharvariable.Point 2:
case '1234'also wrong. Here, the
'1234'does not denote a string. It is a multibyte charcater, which is most probably something you don't want. Again, even you change that to something like"1234", still it would be incorrect, as it will not give you the intended value, and strings cannot be used forcasestatement values.
Solution: Instead of using the switch case here, you can try using strcmp() to compare the incoming string and chose accordingly.
Note: The recommended signature of main() is int main(int argc, char *argv[])
No comments:
Post a Comment