There is no way in C to use a "string" (an array of characters in your case) in a switch statement's condition or in the label constant expressions as they cannot be converted to an integral value. C requires the condition and the constant expressions to be of integral type (cf., for example, this online c++ standard draft):
6.8.4.2 The switch statement
1 The controlling expression of a switch statement shall have integer
type.
...
3 The expression of each case label shall be an integer constant
expression ...
To overcome this, you could use cascades of if (strcmp(whr,"USD")==0) else if (strcmp(whr, "YEN")==0)...
or you could introduce an enum that represents the currencies and map the user input to such enums.
As the if-else
-cascades are straight forward, I just show the second approach. Using enums has the advantage that you can use them easily throughout your program without the need of repeating the if-else
-cascades at different places in your code:
typedef enum {
UNDEFINED, USD, YEN, POUND
} CurrencyEnum;
struct currencyLabel {
CurrencyEnum currencyEnum;
const char *currencyString;
} currencyLabels[] = {
{ USD, "USD" },
{ YEN, "YEN" },
{ POUND, "POUND" }
};
CurrencyEnum getCurrencyByLabel(const char* label) {
for (int i=0; i< (sizeof(currencyLabels) / sizeof(struct currencyLabel)); i++) {
if (strcmp(label, currencyLabels[i].currencyString) == 0)
return currencyLabels[i].currencyEnum; // could use strcasecmp or stricmp, if available, too.
}
return UNDEFINED;
}
int main(void) {
float usd2 = 0.9117;
float yen2 = 0.0073;
float pound2 = 1.4137;
float eingabe;
char whr[10] = "";
printf("Bitte Summe in EURO eingeben: ");
scanf("%f", &eingabe);
printf("Die Währungnummer eingeben USD, YEN, POUND: ");
scanf("%s", whr);
CurrencyEnum currency = getCurrencyByLabel(whr);
switch(currency) {
case USD: printf("%.4f EURO es sind dann %.4f USD.", eingabe, (eingabe/usd2));
break;
case YEN: printf("%.4f EURO es sind dann %.4f YEN.", eingabe, (eingabe/yen2));
break;
case POUND: printf("%.4f EURO es sind dann %.4f POUND.", eingabe, (eingabe/pound2));
break;
default: printf("Falsche eingabe.");
break;
}
return 0;
}
BTW: Note that defining whr
as char whr[] = ""
actually reserves a string with size 1, and using it in scanf
yields an overflow (and undefined behaviour). You can define it as char whr[10]
or something like that.