Search code examples
cstructure

How to make sure that my data does not get overwritten when user inputs new ones? [C Structures & Files]


I am trying to create a program that can contain multiple playlists with multiple songs. My problem is that each playlist seem to only be able to contain one song. When the user inputs a new song, the previous one gets overwritten. What am I doing wrong and how can I fix it?


Solution

  • The field songs is an array. When you do songs->title you access the title of the first element of the array.

    You shall have an index to keep track of the set song. The field song_count seems to be here for that purpose.

    void addSongToPlaylist(struct playlist *playlists, int index){
        int i, choice;
    
        printf("THE PLAYLISTS AVAILABLE ARE:\n");
        for (int i = 0; i < index; i++){
            printf("\t[%d] %s\n", i, playlists[i].name);
        }
    
        printf("\nEnter playlist number: ");
        scanf("%d", &choice);
    
        printf("\nEnter song title: ");
        scanf("%s", playlists[choice].songs[playlists[choice].song_count].title); 
        printf("Enter song artist: ");
        scanf("%s", playlists[choice].songs[playlists[choice].song_count].artist); 
        printf("Enter song album: ");
        scanf("%s", playlists[choice].songs[playlists[choice].song_count].album); 
    
        // Increment sound_count for next time
        playlists[choice].song_count++;
    
        printf("Succesfully added song to playlist!\n");
    }