I am making a scientific calculator as an assignment in my class. I am using switch case for all the operators like +-*/ , and I am calling them with a single keyword like '+' for addition and so on. The problem is that when i try to use more than one word in case statement for mathematical function like Tan, Cos or sin , The program does not calculate anything. I am using char for the cases in switch statement.
here's da snippet of what i am doing (i am showing some part of the program, consider i have already declared all the variables) :

char ch[10];
switch(ch)
	{case 's': // i want to use 'sin' here but the program does not calculate anything after i do so!
		trig= sin(fno*pi/180);
		cout<<endl<<"Sin("<<fno<<") = "<<trig<<endl<<endl;
		break;
	}

Any help will be appreciated... thanks...

switch only works with integral types as the switch_var. You will be limited to one character labels in the switch block.

You could, in validating the input, make a conversion from "words" to single characters. Something like:

char input[20];
char operation;
cout <<"Operation?";
cin >> input;

if( strcmp( input, "sin" ) == 0 )
  operation = 's';
....
switch ( operation )
....

You could use an enum. You can label all of your operations with their proper names but have them evaluated as an integral type for use in a switch statement.

You might need to parse a string to come up with the correct enum value. In that case you can use an array of strings with indices that match the enum. Then you can treat the array of strings like a lookup to get the enum of the operation. Might not be the simplest way, but it'll probably make your code a little more readable.

Here's a rough idea of the code. I haven't checked or run this. If you have problems with it let me know. Also, you'd probably want some error handling, and some code to handle incorrect/unknown inputs etc.

enum Operations {SIN, COS, TAN};
char *szLabels[3] = {"sin", "cos", "tan"};

char *szInput;

// code to get the operation as a string and store it in szInput

int i=0;
while ( strcmp(szInput, szLabels[i]) )
    ++i;

switch (i)
{
    case SIN:
        //handle sin operation
        break;
    
    // other cases here
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.