结构数组程序有未知的编译或分割错误,C++

Array of structures program has unknown compiling or segmantation error, c++

我正在编写这个包含结构的程序,该程序在 repl.it ide 中的第一次迭代后运行然后崩溃,并在我的 cygwin 命令行中运行 2-3 次。我刚开始使用 C++,所以我没有立即看到任何东西,但我相信语法是正确的。该程序将歌曲列表保存在一个空文本文件中,但还将歌曲保存到一个空数组中,以便我以后可能会引用它。

#include<cstdlib> //for random function
#include<ctime> //for random function
#include<string>
#include<fstream>
#include<sstream> //for int to str function
#include<iostream>
using namespace std;

struct HR_PL{
    string name;
    int count;
    char songs[];
};
string intToString(int a);

int main() {
    HR_PL hr[12]; //making 12 instances for our array of structs (12 hours)
    //datatype arrayName[no of elements]
    char song_list[12] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'k'};
    int rand_for_pl;
    char user_response;
    fstream likeFile;

    for (int i = 0; i < 12; i++) {
        hr[i].count = 0;
        //hr[i].songs[10];  Array is created in HR_PL
        cout << "\nHour " << i+1 << " playlist: " << endl;
        hr[i].name = intToString(i+1);
        for (int j = 0; j < 10; j++) {
            rand_for_pl = rand() % 12;
            cout << song_list[rand_for_pl];
            cout << ",";
            hr[i].songs[j] = song_list[rand_for_pl];
        }
        cout << endl << endl;
        cout << "Did you like the playlist? ";
        cin >> user_response;

        if (user_response == 'y') {
            likeFile.open("like.txt", ios::app);  //Create the output file to append
            cout << "Great! We have saved the playlist for you." << endl;
            if (likeFile.is_open()) {
                likeFile << "Hour " << i+1 << " Playlist: ";
                for(int s = 0; s < 10; s++){
                likeFile << hr[i].songs[s];
                likeFile << " ";
            }
            likeFile << "\n";
            }
            likeFile.close();
            }
            else {
                  cout << "Sorry! We hope you will like the upcoming playlist." << endl;
            }
    }//endfor
    return 0;

}//endmain

string intToString(int a){
    ostringstream temp;
    temp << a;
    return temp.str();
};

repl.it link 有文本文件:https://repl.it/@ValerieAndy/PrWorkingwStructs

抱歉,如果这是一种错误的提问方式,我也是新来的。

您当前的代码在

失败
HR_PL hr[12]; //making 12 instances for our array of structs (12 hours)

因为

struct HR_PL{
    string name;
    int count;
    char songs[];
};

正如 πìντα ῥεῖ 指出的那样,是无效的。

char songs[];

无法初始化。

如果您尝试在 HR_PL 中存储 C 字符串,则需要 char*,或者最好是 std::string。如果您尝试存储字符串数组,则最好使用 std::vector<std::string>.

您显示的代码不应编译,因为它不是有效的 C++,但即使它有效,您也会遇到麻烦,因为您没有分配灵活的数组成员 char songs[]; space 为.

这是一个使用 std::vector 数组和 <random> 随机数的版本。我还删除了 using namespace std; 因为这样做是 bad practice.

#include <iostream>
#include <fstream>
#include <string>
#include <random> // for random functions
#include <vector> // instead of using C style arrays

struct HR_PL {
    std::string name{};
    // "count" is not needed, use "songs.size()" instead
    std::vector<std::string> songs{};
};

int main() {
    std::random_device rd;        // used for seeding the pseudo random number generator (PRNG)
    std::mt19937 generator(rd()); // A better PRNG than rand()

    std::vector<HR_PL> hr(12); // making 12 instances for our array of structs (12 hours)

    // datatype arrayName[no of elements]
    std::vector<std::string> song_list = {"a", "b", "c", "d", "e", "f",
                                          "g", "h", "j", "k", "l", "k"};

    // the distribution of the values generated by the PRNG
    std::uniform_int_distribution<uint32_t> song_dist(0, song_list.size() - 1);
    // the distribution and generator placed in a lambda for convenience
    auto random_song = [&]() { return song_dist(generator); };

    int rand_for_pl;
    char user_response;

    for(int i = 0; i < 12; i++) {
        std::cout << "\nHour " << i + 1 << " playlist:\n";
        hr[i].name = std::to_string(i + 1);
        for(int j = 0; j < 10; j++) {
            rand_for_pl = random_song();
            std::cout << song_list[rand_for_pl];
            std::cout << ",";
            // adding songs to the vector can be done using "push_back"
            hr[i].songs.push_back(song_list[rand_for_pl]);
        }
        std::cout << "\n\nDid you like the playlist? ";
        std::cin >> user_response;

        if(user_response == 'y') {
            // Create the output file or append to it:
            std::fstream likeFile("like.txt", std::ios::app);
            // consider moving the below output until the playlist is actually saved
            std::cout << "Great! We have saved the playlist for you.\n";
            if(likeFile) { // in bool context, likeFile is true if opened
                likeFile << "Hour " << i + 1 << " Playlist: ";
                for(int s = 0; s < 10; s++) {
                    likeFile << hr[i].songs[s];
                    likeFile << " ";
                }
                // the loop above would be better written like this:
                /*
                for(const std::string& song : hr[i].songs) {
                    likeFile << song << " ";
                }
                */
                likeFile << "\n";
            }
            // likeFile closes when it goes out of scope so you don't have to
        } else {
            std::cout << "Sorry! We hope you will like the upcoming playlist.\n";
        }
    } // endfor
    return 0;

} // endmain