开发者

How do I use the switch statement?

I am trying to understand the switch statement better. I don't ne开发者_如何学Goed the code but kinda a walkthrough on how it would be done.

If someone enters a 7 digit phone number EG. 555-3333 but enters it as "jkl-deff" as it would correspodnd to the letters on the dial pad, how would I change the output back to numbers?

Would this work:

switch (Digit[num1])
  case 'j,k,l':
              num1 = 5;
              break;
  case 'd,e,f':
              num1 = 3;
              break;


To do that with a switch statement, you'd have to walk through the char array, switching on each character. Group all the chars that have the same number together.

Something like

switch (phoneChar[i])
case 'a':
case 'b':
case 'c':
   newChar[i] = '2';
   break;

That said, I'm not sure that switch case is the best way to do that. I don't know what would be the best off the top of my head, but something feels wrong about this :)

Edit The i would be the index of the current character under consideration. You'll have a 7 (or 8 or 10 or 12 character string depending on formatting) for a phone number. You'd have to take each character at a time.. so phone[0] = 'j' in the above example.


I would not use a switch!

// A,B,C => 2;  D,E,F => 3 etc.
static int  convert[] = {2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9};


for(int loop =0 ;loop < Digit.size(); ++loop)
{
    num = convert[Digit[loop] - 'a'];
                  // Thus the character 'a' gets mapped to position 0
                  //      the character 'b' gets mapped to position 1 etc.
    // num is then the character mapped into the covert[] array above.  
}


You could probably do it like this:

if (islower(c)) { num=(c-'a')/3; num = 2 + (num==8) ? 7 : num; }

to convert a character to a phone pad digit. The num==8 part at the end handles the exra digit on the 9 key.

Altogether it would look like this:

char c = getNextCharacterSomehow();
int num = -1;

if (isdigit(c)) num = c-'0';
else if (islower(c)) { num=(c-'a')/3; num = 2 + (num==8) ? 7 : num; }
else if (isupper(c)) { num=(c-'A')/3; num = 2 + (num==8) ? 7 : num; }

Also, a note about the switch statement: The item that comes between the "case" and the ":" has to have the same type as the thing specified by the "switch()" portion. And that type must be a scalar, which excludes things like strings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜