How to avoid a lot of switch case

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • silusilusilu@gmail.com

    How to avoid a lot of switch case

    I wrote ,as homework, a program that displays words after key pressed.
    So, if letter 'A' is pressed, the word 'dog' appears; if letter 'B' is
    pressed 'cat' appears; if letter 'a' is pressed 'apple' appears; and
    so on...
    I wrote this program with a lot of switch case, so i want to obtain a
    smaller program (if possible)...can you help me?
  • Szabolcs Borsanyi

    #2
    Re: How to avoid a lot of switch case

    On Thu, May 29, 2008 at 11:26:34PM -0700, silusilusilu@gm ail.com wrote:
    I wrote ,as homework, a program that displays words after key pressed.
    So, if letter 'A' is pressed, the word 'dog' appears; if letter 'B' is
    pressed 'cat' appears; if letter 'a' is pressed 'apple' appears; and
    so on...
    I wrote this program with a lot of switch case, so i want to obtain a
    smaller program (if possible)...can you help me?
    What you would like to do is to map integers to strings.

    How about an array?
    const char *my_lovely_word s[UCHAR_MAX];

    Please stop reading here, try to write the program, and then you may continue.

    my_lovely_words['a']="apple";
    ....
    But I do not see how that would save you much keystrokes.

    In C99 you can have named initialisers
    const char *my_lovely_word s[]={
    ['A']="dog",
    ['a']="apple",
    };

    Szabolcs


    Comment

    • vippstar@gmail.com

      #3
      Re: How to avoid a lot of switch case

      On May 30, 9:52 am, Szabolcs Borsanyi <s.borsa...@sus sex.ac.ukwrote:
      On Thu, May 29, 2008 at 11:26:34PM -0700, silusilus...@gm ail.com wrote:
      I wrote ,as homework, a program that displays words after key pressed.
      So, if letter 'A' is pressed, the word 'dog' appears; if letter 'B' is
      pressed 'cat' appears; if letter 'a' is pressed 'apple' appears; and
      so on...
      I wrote this program with a lot of switch case, so i want to obtain a
      smaller program (if possible)...can you help me?
      >
      What you would like to do is to map integers to strings.
      >
      How about an array?
      const char *my_lovely_word s[UCHAR_MAX];
      >
      Please stop reading here, try to write the program, and then you may continue.
      >
      my_lovely_words['a']="apple";
      And what if 'a' has the value 4325? It would waste a lot of space.
      Here's another solution:

      const char *my_lovely_word s[] = { ... };
      const char *p, str[] = "#Az";
      int c;
      ....
      if(p = strchr(str, c)) != NULL) printf("%c = %s\n", c,
      my_lovely_words[p - str]);

      Comment

      Working...