I'm used to if/else. Can someone tell me if this correct or not. It's not pulling up an error but it's not outputting what I want it to output either. Thank you!

char pick;
cin >> pick;

if(pick == 'a' || pick == 'A')
    stuff inside here

//For case switch... can you do the following:

switch(pick)
{
case ('a' || 'A'):
    stuff here;
    break;
case ('b' || 'B'):
    stuff here;
    break;
}

Recommended Answers

All 5 Replies

I'm not sure you can use char in switch condition.
But if you could it would look like this.

char pick;
cin >> pick;
if(pick == 'a' || pick == 'A')
    stuff inside here
//For case switch... can you do the following:
switch(pick)
{
case 'a':
case 'A':
    stuff here;
    break;
case 'b':
case 'B':
    stuff here;
    break;
}

You may need to add a bit more code.

Alright thanks a lot.

You can use a char in a switch. The reason that your first attempt failed is that a switch statement expects constant values in the case labels. So ('a' || 'A') evaluates to true (most likely 1). Therefor you get a final expression that looks something like:

switch (pick) {
   case 1:
      stuff here
      break;
   case 1:
      other stuff here
      break;
}

So if pick is 1 you will execute the first case statement otherwise you will execute nothing.

As an aside, if you are taking in case-insensitive user input as you are here, I would suggest using either toupper() or tolower() to set the case of the switch variable, thus avoiding the issue entirely.

But how can i write the following code in switch statement. It is in indexed array
commands[0] = (char )"ls"; params[0] = (char)0;
commands[1] = (char )"who"; params[1] = (char)0;
commands[2] = (char )"date"; params[2] = (char)"+%d/%m/%y";
commands[3] = (char )"ps"; params[3] = (char)"-f";
commands[4] = (char )"echo"; params[4] = (char)"Zafar Ullah";

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.