How to avoid a lot of switch case

S

silusilusilu

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?
 
S

Szabolcs Borsanyi

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_words[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_words[]={
['A']="dog",
['a']="apple",
};

Szabolcs
 
V

vippstar

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_words[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_words[] = { ... };
const char *p, str[] = "#Az";
int c;
....
if(p = strchr(str, c)) != NULL) printf("%c = %s\n", c,
my_lovely_words[p - str]);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top