货币转换代码不起作用 - 如何比较字符串

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

我正在制作一个简单的货币转换器,将瑞典克朗转换为欧洲欧元或美国美元。 当它应该打印出转换时,程序只是终止了。 Visual Studio 代码说代码没有问题所以我不明白这是为什么。

代码:

#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;
}

C 中的字符串比较使用 strcmp() 函数。你不能用

 if (currency == "USD")

添加#include <string.h>然后

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

另请注意,不测试来自 scanf 的 return 值始终是一个错误。你认为你可以假设输入是格式正确的,但尤其是用户输入通常不是。

接下来,读取字符串不能使用%c,必须使用%s。不要盲目地这样做,关于如何限制输入的大小以免溢出你的 currency[] 数组有很多问题。搜索他们。如果提到fgets(),仔细看看

您还应该养成在字符串的 末尾 处编写换行符 \n 的习惯,因为那是刷新行缓冲输出的时间("appears"). Windows 在程序结束时总是附加一个换行符有点不对劲,这导致了 printf ("\nwhatever").

这种常见的可憎行为

这段代码有两个主要问题:

  1. 使用 scanf 时,您正在等待 char * 输入,但 %c 正在接受 char。 将其更改为 %s。
  2. C 不允许使用“==”运算符进行字符串比较。您应该改用 strcmp()。