首页 > 解决方案 > 为什么我不能将字符串添加到结构中?

问题描述

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

#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");
    }
}

标签: cstringstruct

解决方案


由于这里的问题是关于在 a 中存储字符串,所以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);
}

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

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


推荐阅读