如何在 C 中分配新的字符串值

How to assign new string values in C

我的简单计算器正在尝试显示用户选择的操作。我知道在 C 中,字符串必须声明为一维字符数组。

int a, b;
int oper; //operation number
char operName[15];

printf("\nEnter two numbers: ");
scanf("%d%d", &a, &b);
printf("\nYou entered: %d and %d", a, b);

printf("\nChoose operation:"
        "\n1 = +"
        "\n2 = -"
        "\n3 = x"
        "\n4 = /");
scanf("%d", &oper);

代码编译运行。但是当执行开关块时,它停止工作。我正在使用 switch 选择适当的操作名称,并将其分配给 operName(这样我就可以在执行实际操作之前显示所选的操作)。

switch(oper){
    case 1:
        operName == "Addition";
        break;  
    .
    .
    .
    default:
        operName == "Invalid input";
}

printf("\n\nYou chose: %s", oper);

我在某处读到我需要使用指针来防止内存泄漏,但我是新手,所以也许有更简单的方法。

== 不可赋值。 C 是一种非常低级的语言,您不能像为整数或字符那样为 C 中的字符串赋值。

为此,您必须使用标准库 string.h

例如:

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

int main(void)
{
    char source[1000], destination[1000];

    /* Do something with the strings */

    strcpy(destination, source);
    return 0;
}

了解更多关于 string.h here