c - C 中函数指针的数组。如何使用枚举从数组中选择我想要的元素?

标签 c arrays function pointers

我希望用户输入一个像 ADD 或 SUB 这样的值来执行所需的操作,但我得到“数组下标不是整数”。我知道我可以输入数字,例如 0、1、2 等,因为枚举的工作原理,但我想让它更加用户友好。我在网上也找不到任何关于这方面的信息,我的书也没有帮助。请帮忙!

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

int multiply(int , int);
int sum(int, int);
int divide(int, int);
int sub(int, int);

int(*calc[])(type) = {sum, sub, multiply, divide};
enum response{ADD, SUB, MULT, DIV};
enum response type;

int main()
{
    int a, b;
    char s[4];
    printf("Enter two numbers and the operation. Operations: ADD, SUB, MULT, DIV");
    scanf("%d %d %s", &a, &b, &s);
    printf("The result = %d",(calc[s])(a, b));
    return 0;
}
int multiply(int a, int b)
{
    return a*b;
}

int sub(int a, int b)
{
    return a-b;
}
int sum(int a, int b)
{
    return a+b;
}
int divide(int a, int b)
{
    return a/b;
}



最佳答案

枚举常量本质上是整数常量的符号名称。它们与字符串不同,因此不能直接使用后者来替代前者。

您需要检查给定字符串的值并根据该值选择适当的枚举。

enum response getResponse(const char *str)
{
    if (!strcmp(str, "ADD")) {
         return ADD;
    } else if (!strcmp(str, "SUB")) {
         return SUB;
    } else if (!strcmp(str, "MULT")) {
         return MULT;
    } else if (!strcmp(str, "DIV")) {
         return DIV;
    } else {
         return (enum response)-1;
    }
}

int main()
{
    int a, b;
    char s[4];
    scanf("%d %d %4s", &a, &b, s);
    enum response resp = getResponse(s);
    if (resp == (enum response)-1) {
        printf("invalid operation\n");
    } else {
        printf("The result = %d",(calc[resp])(a, b));
    }
    return 0;
}

此外,calc 的类型不正确。它应该指定数组成员的每个参数的类型:

int(*calc[])(int, int) = {sum, sub, multiply, divide};

关于c - C 中函数指针的数组。如何使用枚举从数组中选择我想要的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59630184/

相关文章:

c - x86 汇编代码基本

c - CLOCK_TAI 的纪元是什么?

使用 sprintf()/write() 的 C 程序有多余字符

python - 在 Python 中向数组追加行,String 对象没有属性追加

来自《Kivy Blueprints》一书的 Python kivy 代码

Python函数的参数默认值是从另一个模块导入的

c - 在 Xcode 上测试纯 C 代码?

java - 搜索数组中的元素并返回它

组合字节数组以接受可变数量的参数

javascript - boolean 测试作为参数