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

标签 c arrays string switch-statement calculator

我的简单计算器正在尝试显示用户选择的操作。据我了解,在 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 block 时,它停止工作。我使用 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

关于c - 如何在 C 中分配新的字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43405258/

相关文章:

我可以在 pthread_kill 中使用 0 作为信号参数吗

c - "->"在C编程、Gtk+编程中代表什么?

c - 在 CUDA 中实现固定精度数字

javascript - 在数组元素 React 之间切换

c++ - 使用标准模板库中的堆栈

使用 C 宏调用关联*函数

arrays - PowerShell-无法导出到CSV文件

c 在泛型数组中搜索

java - 将哈希字节数组转换为字符串

arrays - 当字符与前一个字符不同时,在 ruby​​ 中分割字符串