我想解析文件的内容并加载到 map 中。
这是文件内容格式:
Movie-name release-year price cast ishd
"DDLG" 2010 20.00 "shahrukh and Kajal" true
"Aamir" 2008 10.00 "abc, xyz and ijkl" false
map 的键将是第一个单词(电影名称)。
类定义:
class movieInfo
{
private:
int releaseYear;
double price;
string cast;
bool isHD;
};
这是我要实现的功能。
void fill_map_contents (map <string, movieInfo*> &mymap, ifstream& myfile)
{
string line;
string word;
while (getline(myfile, line))
{
out << "inside while loop " << line << endl;
stringstream tokenizer;
tokenizer << line;
movieInfo *temp = new movieInfo;
while (tokenizer >> word)
{
cout << " printing word :->"<< word << endl;
//temp->releaseYear = atoi(word);
//temp->price = 12.34;
//temp->cast = "sahahrukh salman";
//temp->isHD = false;
mymap[word] = temp;
}
delete temp;
}
}
我不知道在 while (tokenizer >> word) 之后如何填充对象变量并将其分配给映射。
我们将不胜感激任何帮助。
开发
最佳答案
cout << " printing word :->"<< word << endl;
//temp->releaseYear = atoi(word);
//temp->price = 12.34;
//temp->cast = "sahahrukh salman";
//temp->isHD = false;
在上面的代码中,您试图直接访问类的私有(private)成员,这是不可能的。因此,更好的解决方案是您应该为每个变量包含公共(public) getter/setter,如下所示。
public:
void setreleaseYear(int sry){releaseYear=sry;}
void setprice(double pr){price=pr;}
void setcast(string cast){string=str;}
void setisHD(bool id){isHD=id;}
现在代替注释代码使用:
//temp->releaseYear = atoi(word);
temp->setreleaseYear(atoi(word));
tokenizer >> word;
//temp->price = 12.34;
temp->setprice(atof(word));
tokenizer >> word;
//temp->cast = "sahahrukh salman";
temp->setcast(word);
tokenizer >> word;
//temp->isHD = false;
temp->setisHD(word);
不需要 while 循环。
关于c++ - 如何解析文件内容并加载到 map 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19704854/