Subject: Invalid conversion from 'char*' to 'char'
Posted By: deuxmio Post Date: 12/7/2006 4:08:05 AM
I'm trying to write a calculator that takes command line arguments. So if someone wants to add 2 and 2 they would type:

$./prog a 2 2


argv[1] would be the desired operation, while argv[2] and argv[3] would be the numbers. This is my code so far:


#include <iostream>
#include <cmath>
#include <cstdlib>

using namespace std;

int addition(int a, int b){
int c;
c=a+b;
return (c);
}


int main(int argc, char    *argv[]){
char x(argv[1]);
int a, b;
a = atoi(argv[2]);
b = atoi(argv[3]);


switch (x) {
    case "a":
        addition(a,b);
        break;
    default:
        cerr << "Undefined operation.";
}

return 0;

}


Every time I try to compile this GCC gives me these errors:

 In function 'int main(int, char**)':
 error: invalid conversion from 'char*' to 'char'
 error: case label does not reduce to an integer constant
make: *** [calcpp] Error 1

How can I use the value of argv[1] in a switch statement? My best attempts at deciphering the error messages point to that. Thanks in advance.


Reply By: Geo121 Reply Date: 12/7/2006 7:51:39 AM
Hey there. Your only problem is that you are declaring it right just forgetting to follow up.

Basically you declare char *argv in your main function

which was right but when you declared char x = argv[1] you forgot to say it was a pointer

so all you do is add an asterisk in front of argv[1] and you have it as a char =P

now as far as the switch statement . . .

it will accept characters as long as you put them in as characters

so this step depends on your compiler but the best practice is to put characters in single quotes

mainly becouse this is the most common standard and most compilers dont like chars in double quotes

so if you say 'a' instead of "a" it works

I did it myself heres the code :

#include <iostream>
#include <cmath>
#include <cstdlib>

using namespace std;

int addition(int a, int b) {
     int c;
     c=a+b;
     return (c);
}


int main(int argc, char *argv[]) {
     char x = *argv[1];
     int a, b;
     a = atoi(argv[2]);
     b = atoi(argv[3]);


     switch(x) {
          case 'a':
               cout << addition(a,b);
               break;
          default:
               cerr << "Undefined operation.";
     }

     return 0;
}


 ~ Geo

 ~ You are unique, just like everyone else
Reply By: deuxmio Reply Date: 12/7/2006 12:25:00 PM
Thanks a lot Geo! That did the trick.

Reply By: Geo121 Reply Date: 12/8/2006 6:56:21 AM
No problemo! That's what I'm here for =P

Keep up the good work!

 ~ Geo

 ~ You are unique, just like everyone else

Go to topic 53369

Return to index page 98
Return to index page 97
Return to index page 96
Return to index page 95
Return to index page 94
Return to index page 93
Return to index page 92
Return to index page 91
Return to index page 90
Return to index page 89