Home > database >  Why can't I add a string to a structure?
Why can't I add a string to a structure?

Time:10-28

So I'm trying to create a program that reads data into a file. But before that I need to store the data into a struct. How do I store a string in a struct?

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

CodePudding user response:

As the question here is about storing strings in a struct, here is a bare-bones solution:

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

This program just demonstrates storing a string in a struct. Here, 20 is the maximum number of characters (including the terminating NUL) you can store in singer or song. Optionally, you could also allocate memory dynamically using malloc() for the strings to store.

Please note that several other problems with your program. For e.g. your loop never ends and a } is missing.

  • Related