我正在编写包含结构的程序,该程序在 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 链接:https ://repl.it/@ValerieAndy/PrWorkingwStructs
抱歉,如果这是提出问题的错误方式,我也是新来的。