【问题标题】:Why can't I add a string to a structure?为什么我不能将字符串添加到结构中?
【发布时间】:2021-12-12 21:18:15
【问题描述】:

所以我正在尝试创建一个将数据读入文件的程序。但在此之前,我需要将数据存储到一个结构中。如何将字符串存储在结构中?

#include <stdio.h>
#define MAX 100

int count;

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

int main() {
    while (1) {
        printf("Name of band of Singer: ");
        scanf_s("%s,", &hold[count].singer);

        printf("Name of Song: ");
        scanf_s("%c", &hold[count].song);

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

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

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

【问题讨论】:

  • 代替char singer, song; 使用char singer[100], song[200]; 代表最多99 个字符的歌手和最多199 个字符的歌曲。
  • 或者考虑使用指向动态分配的字符数组的指针。

标签: c string struct


【解决方案1】:

由于这里的问题是关于将字符串存储在 struct 中,因此这是一个简单的解决方案:

#include <stdio.h>

#define MAX 100

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

int main() {
        printf("Name of band of Singer: ");
        fgets(hold[0].singer, 20, stdin);
        printf("Singer: %s\n", hold[0].singer);
}

这个程序只是演示了在结构中存储一个字符串。这里,20 是您可以在singersong 中存储的最大字符数(包括终止符NUL)。或者,您还可以使用 malloc() 动态分配内存以存储要存储的字符串。

请注意您的程序还有其他几个问题。例如您的循环永远不会结束,并且缺少 }

【讨论】:

  • 感谢您回答我的问题。原始代码要长得多,我只复制了需要帮助的部分。对于其他变量,我可以使用 scanf 对吗?
  • 避免混合 fgets 和 scanf。还记得 fgets 在末尾包含换行符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-10
  • 2021-10-22
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
相关资源
最近更新 更多