You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么不能向C语言结构体中存入字符串?结构体存储字符串实现方法

C语言结构体存储字符串的解决方法

你的代码无法存储字符串的核心原因是结构体中的singer和song字段定义为单字符char类型,char类型仅能存储1个ASCII字符,无法存储由多个字符组成的字符串,需按以下步骤修改:


1. 修改结构体字段定义

将单字符字段替换为固定长度的字符数组,数组长度可根据实际存储的字符串最大长度调整,示例如下:

struct cg {
    float price;
    char singer[50]; // 可存储最长49个字符的歌手名(最后1位存字符串结束符\0)
    char song[50];   // 可存储最长49个字符的歌曲名
    int release;
} hold[100];

2. 修正输入逻辑

你使用的scanf_s是微软安全标准的输入函数,读取字符串时需要额外传入数组长度参数,同时需要处理输入后残留的换行符,避免后续读取到空内容:

  • 数组名本身就是内存首地址,读取字符串时不需要加取地址符&
  • 增加数组边界判断,避免count超过100时出现内存越界

修改后的完整可运行代码如下:

#include <stdio.h>
#define MAX 100

int count;

struct cg {
    float price;
    char singer[50];
    char song[50];
    int release;
} hold[100];

int main() {
    while (count < 100) { // 边界判断防止数组越界
        printf("Name of band of Singer: ");
        scanf_s("%s", hold[count].singer, sizeof(hold[count].singer));
        getchar(); // 吃掉缓冲区残留的换行符

        printf("Name of Song: ");
        scanf_s("%s", hold[count].song, sizeof(hold[count].song));
        getchar();

        printf("Price: ");
        scanf_s("%f", &hold[count].price);
        getchar();

        printf("Year of Release: ");
        scanf_s("%d", &hold[count].release);
        getchar();

        count++;
        printf("\n");
    }
    return 0;
}

补充说明

如果需要存储带空格的歌手名/歌曲名,可以把输入格式符%s替换为%[^\n],即可匹配到换行符之前的所有字符(包括空格)。

内容的提问来源于stack exchange,提问作者Python Asker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 22:54:03