我正在尝试制作一个程序,从文本文件中读取有关DVD信息的行。在将信息提供给自定义DVD类后,我将打印它。目前,在使用调试器时,它会为自定义类的每个参数显示以下错误。请帮忙。
读取字符串
的字符时出错
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;
class dvd
{
string movieName, movieProdComp, movieLeadActor, movieLanguage, renterName;
string releaseYear, rentDate, returnDate;
public:
dvd() {};
dvd(string line) {};
dvd(string mn, string mpc, string mla, string ml, string rn, string ry, string rd, string retd);
void print();
};
dvd::dvd(string mn, string mpc, string mla, string ml, string rn, string ry, string rd, string retd) {
movieName = mn;
movieProdComp = mpc;
movieLeadActor = mla;
movieLanguage = ml;
renterName = rn;
releaseYear = ry;
rentDate = rd;
returnDate = retd;
}
void dvd::print() {
cout << "Movie:" << movieName << endl;
cout << "Production:" << movieProdComp << endl;
cout << "Starring:" << movieLeadActor << endl;
cout << "Language:" << movieLanguage << endl;
cout << "Rented By:" << renterName << endl;
cout << "Released:" << releaseYear << endl;
cout << "Rent Date:" << rentDate << endl;
cout << "Return Date:" << returnDate << endl;
}
int main() {
string filepath = "C:\\Users\\SuperUser\\Google Drive\\COMP306\\TMA2\\test.txt";
string line;
ifstream file(filepath);
string arrayDvd[10][8];
if (file.is_open())
{
int i = 0;
int c = 0;
int n = 0;
while (getline(file, line))
{
arrayDvd[n][c] = line;
i++;
c++;
if (i > 7)
{
n++;
c=i = 0;
}
}
}
for (int n = 0; n <= 9; n++)
{
//this is where the error shows.
dvd dvdS[] = { arrayDvd[n][0], arrayDvd[n][1], arrayDvd[n][2], arrayDvd[n][3], arrayDvd[n][4], arrayDvd[n][5], arrayDvd[n][6], arrayDvd[n][7] };
}
}
数据:以下字符串重复10次。 Full data
Zombie1
BBC
詹姆斯
英语
ALW
2012
20170601个
20170630
答案 0 :(得分:0)
更改
dvd dvdS[] = { arrayDvd[n][0], arrayDvd[n][1], arrayDvd[n][2], arrayDvd[n][3], arrayDvd[n][4], arrayDvd[n][5], arrayDvd[n][6], arrayDvd[n][7] };
到
dvd dvdS{ arrayDvd[n][0], arrayDvd[n][1], arrayDvd[n][2], arrayDvd[n][3], arrayDvd[n][4], arrayDvd[n][5], arrayDvd[n][6], arrayDvd[n][7] };
前者使用一个参数构造函数创建一个包含8个实例的c样式数组(不执行任何操作),后者使用8参数构造函数创建一个实例。
答案 1 :(得分:0)
我相信你想要这样的东西
std::vector<dvd> dvds;
for (int n = 0; n <= 9; n++)
{
dvds.push_back(dvd(arrayDvd[n][n*7+0], arrayDvd[n][n*7+1], arrayDvd[n][n*7+2], arrayDvd[n][n*7+3], arrayDvd[n][n*7+4], arrayDvd[n][n*7+5], arrayDvd[n][n*7+6], arrayDvd[n][n*7+7]));
}
这将创建一个数组(由std :: vector包装)并将每个dvd对象推入其中。此外,您不需要变量i
删除它,而不是检查i > 7
检查是否c > 7