【发布时间】:2021-11-11 20:52:25
【问题描述】:
对于家庭作业,我应该创建一个程序,该程序使用结构来保存艺术家的唱片信息;即名称、开始年份、结束年份、流派(可以不止一个)和专辑及其发行年份(我将其解释为第二种结构)。所有这些信息都应该从一个文件中读取。
我在将文件中的数据读取到结构变量中时遇到了一些问题。我的主要问题是我的几个结构变量可以包含多个字符串,我对如何将它们作为单独的值读入变量感到困惑。我试过使用二维数组,但这似乎不起作用,所以我认为向量可能是要走的路,但这似乎也引发了问题。文件格式如下:
artist name
artist genres;....;...
start year
end year
number of albums
album name, album year; ..., ...;
到目前为止,这是我编写的代码:
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Discography {
vector<string> trackTitle;
vector<int> trackYear;
};
struct Artist {
string artistName;
vector<string> genres;
int startingYear;
int endingYear;
int numOfTracks;
struct Discography disc;
};
istream& operator>>(istream& input, Artist& artist)
{
input >> artist.artistName;
//input >> artist.genres;
input >> artist.startingYear;
input >> artist.endingYear;
input >> artist.numOfTracks;
//input >> artist.disc.trackTitle;
//input >> artist.disc.trackYear;
return input;
}
void displayFileContents();
void searchByName();
void searchByGenre();
void searchBySong();
void searchByYear();
int main()
{
/*integer variable for menu selection*/
int selection;
vector<Artist> art;
do
{
cout << "\nPlease make a selection from one of"
<< "\nthe six options below.\n";
cout << "\n1. Display All Information\n";
cout << "2. Search by artist name\n";
cout << "3. Search by genre\n";
cout << "4. Search by song title\n";
cout << "5. Search by an active year\n";
cout << "6. Exit Program\n";
cout << "\nEnter your selection: ";
/*reading user menu selection*/
cin >> selection;
if (selection == 1) {
displayFileContents();
}
else if (selection == 2) {
searchByName();
}
else if (selection == 3) {
searchByGenre();
}
else if (selection == 4) {
searchBySong();
}
else if (selection == 5) {
searchByYear();
}
else if (selection == 6) {
cout << "Good Bye!";
}
else {
cout << "You did not enter a valid selection\n\n";
}
} while (selection != 6);
return 0;
}
void displayFileContents() {
ifstream artistFile;
artistFile.open("My Artists.txt");
Artist a[5];
if (!artistFile.is_open()) {
cout << "File could not open";
}
else
while (std::getline(artistFile, a->artistName)) {
std::cout << a->artistName << "\n";
}
}
void searchByName() {
}
void searchByGenre() {
}
void searchBySong() {
}
void searchByYear() {
}
最终目标是显示信息,并能够根据年份或艺术家姓名或流派等特定内容搜索信息。程序的那部分我觉得很舒服,但文件阅读真的让我难过。向正确方向轻推将不胜感激。提前致谢。
【问题讨论】:
标签: c++