c - C 有没有办法比较多个字符串? [我通过fgets()输入它们]

标签 c string stdin fgets fflush

int Distance() {
    char from[40], to[40];
    double val;
    double result;

    printf("Enter what you want to convert from: ");
    fflush(stdin);
    fgets(from, 40, stdin);

    printf("Enter what you want to convert to: \n");
    fflush(stdin);
    fgets(to, 40, stdin);

    printf("Enter the numerical value of conversion: \n");
    scanf("%lf", &val);

    (strcmp(from, "cm") == 0 && strcmp(to, "mm") == 0) ? printf("Answer is %lf MilliMeters", val / 10) : 
    (strcmp(from, "mm") == 0 && strcmp(to, "cm") == 0) ? printf("Answer is %lf CentiMeters", val * 10) :
    (strcmp(from, "cm") == 0 && strcmp(to, "km") == 0) ? printf("Answer if %lf KiloMeters", val * 100000) : 
    (strcmp(from, "km") == 0 && strcmp(to, "cm") == 0) ? printf("Answer is %lf CentiMeters", val / 100000) : 
    (strcmp(from, "mm") == 0 && strcmp(to, "km") == 0) ? printf("Anser is %lf KiloMeters", val  * 1000000) : 
    (strcmp(from, "km") == 0 && strcmp(to, "mm") == 0) ? printf("Answer is %lf  MilliMeters", val / 1000000) : 
    printf("Please enter valid conversion units");
}

我正在尝试制作一个单位转换器。所以我为不同的转换制作了不同的函数 - 例如int distance()int time() 等等。

在计算距离的函数中,我使用 fgets() 来获取多字符输入,例如“cm”、“mm”等。 我想要实现的是 如果 char from 中的 fgets 值为“任何字符串”,并且 char to 中的 fgets 值为“任何其他字符串” ": 打印结果,其公式为-----(something)

不计算结果,直接跳转到最终的printf("请输入有效的换算单位")

我仍处于初级学习阶段,这可能是一个小错误,请帮忙。

最佳答案

代码中存在多个问题:

  • fgets() 将尾随换行符存储在目标数组的末尾,因此与单位字符串的所有比较都将失败。
  • 您应该使用中间单元以避免测试所有组合。

这是修改后的版本:

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

struct unit {
    double factor;
    const char *abbrev, *singular, *plural;
} const units[] = {
    { 1, "mm", "millimeter", "millimeters" },
    { 10, "cm", "centimeter", "centimeters" },
    { 100, "dm", "decimeter", "decimeters" },
    { 1000, "m", "meter", "meters" },
    { 10000, "dam", "decameter", "decameters" },
    { 100000, "hm", "hectometer", "hectometers" },
    { 1000000, "km", "kilometer", "kilometers" },
    { 25.4, "in", "inches", "inches" },
    { 304.8, "ft", "foot", "feet" },
    { 914.4, "yd", "yards", "yards" },
    { 201168, "fur", "furlong", "furlongs" },
    { 1609344, "mi", "mile", "miles" },
};

int get_unit(void) {
    char buf[40];
    while (fgets(buf, sizeof buf, stdin)) {
        buf[strcspn(buf, "\n")] = '\0';   // remove the newline if any
        for (int i = 0, n = sizeof(units) / sizeof(*units); i < n; i++) {
            if (!strcmp(buf, units[i].abbrev)
            ||  !strcmp(buf, units[i].singular)
            ||  !strcmp(buf, units[i].plural)) {
                return i;
            }
        }
        printf("unknown unit\n");
    }
    printf("unexpected end of file, aborting\n");
    exit(1);
}

int main(void) {
    int from, to;
    double val;

    printf("Enter what you want to convert from: ");
    from = get_unit();

    printf("Enter what you want to convert to: ");
    to = get_unit();

    printf("Enter the numerical value of conversion: ");
    if (scanf("%lf", &val) == 1) {
        double result = val * units[from].factor / units[to].factor;
        printf("Answer is %g %s\n", result, result == 1 ? units[to].singular : units[to].plural);
        return 0;
    }
    return 1;
}

关于c - C 有没有办法比较多个字符串? [我通过fgets()输入它们],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76627995/

相关文章:

c - C中的空终止字符串

postgresql - psycopg2.ProgrammingError : syntax error at or near "stdin" error when trying to copy_from redshift

c - 使用 C 处理标准输入

c - c二叉搜索树中的段错误11

string - 用于在目录和所有子目录中查找字符串的批处理脚本

c++ - 如何检查用户是否给出了正确的数据类型

javascript - 为什么在 javascript 中使用 for in 循环时字符串不匹配

java - 使用标准输入通过/proc/{pid}/fd/0 向 java -jar 发送命令

c - 在 c 中调用 select 后超时是否改变?

objective-c - 你能帮我理解指针吗?