Search code examples
cstringinputcomparisoncurrency

Currency Conversion code isn't working - how to compare strings


I'm making a simple currency converter, converting from Swedish SEK to European EUR or American USD. When it should be printing out the conversion, the program just terminates instead. Visual Studio Code says there are no problems with the code so I don't understand the reason for this.

Code:

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    float SEK;
    const float EUR = 0.0920;
    const float USD = 0.1000;
    const float YEN = 10.7600;
    char currency [256];

    printf("Enter amount of money you want to convert in SEK: ");
    scanf("%f", &SEK);
    printf("Enter the desired currency to convert to: ");
    scanf(" %c", &currency);

    if (currency == "EUR") {
        printf("\nFor %.4f SEK, you get: %.4f EUR", SEK, SEK*EUR);
    }
    else if (currency == "USD") {
        printf("\nFor %.4f SEK, you get: %.4f USD", SEK, SEK*USD);
    }
    getchar();
    getchar(); //used to give me a proper end on output of my program
    return 0;
}

Solution

  • String comparison in C uses the strcmp() function. You can't do it with

     if (currency == "USD")
    

    Add #include <string.h> and then

     if (strcmp (currency, "USD") == 0)
    

    Also note that not testing the return value from scanf is always a bug. You think you can assume input is well-formed, but especially user input is often not.

    Next, to read a string you can't use %c, but must use %s. Don't do it blindly, there are a lot of questions on SO how to limit the size of input as not to overflow your currency[] array. Search for them. If it mentions fgets(), take a closer look.

    You should also get into the habit of writing your newlines \n at the end of a string, because that's when line-buffered output is flushed ("appears"). Windows is kind of broken in always appending a newline when a program ends, which leads to this frequently seen abomination of printf ("\nwhatever").