我用我认为是读取文件错误的作业完成了作业。出于显而易见的原因,我不想发布我的所有代码。我们正在春假,我可能会在几周内得到我教授的反馈。我似乎总是很难阅读文件,所以我想在本周有时间的时候弄清楚。
赋值的要点是创建一个简单的person对象,其中包含一个包含字符串“gift”的STL set容器和一个包含名称作为数据成员的字符串。然后,有一组这些对象。该程序的第一个方面是读取具有以下格式的文件,其中行上的第一个单词始终是名称,引号之间的内容是礼物的想法:
Tom "iphone"
Bill "guitar"
Bill "pencils"
Steve "speaker"
Mary "tennis racket"
Jenny "golf balls"
John "printer"
Bill "books"
Mary "books"
打印到屏幕时,格式应为:
Bill books, guitar, pencils
Jenny golf balls
John printer
Mary books, tennis racket
Steve speaker
Tom iphone
在视觉工作室,一切都很好。但是,当我使用gcc编译和运行时,输出看起来像:
, pencilsooks
Jenny golf balls
John printer
Mary books, tennis racket
Steve speaker
Tom iphone
休息几天后,看着我的readfile函数,我注意到一些不稳定的东西,它不是一个写得很好的函数。也就是说,在VS调试时,一切似乎都有效。当我连接到学校的linux服务器来测试gcc时,出了问题,但我不知道如何在Linux中调试,就像我在VS中那样(我需要学习的东西)。
无论如何,这是我的readfile函数:
//library facilities used: fstream, assert
//Postcondition: set of person objects have been created from file
void read_file(const char* file_name, set<person> &list)
{
ifstream infile;
infile.open(file_name);
assert(infile);
while( infile.good() )
{
string tmp_name; //stores name from file
string tmp_gift; //stores gift from file
person p_tmp; //to be added to person_list
set<person>::iterator people_iter;
infile >> tmp_name;//get 1st name in file
//check to see if it's in the set of people
if( in_list(tmp_name, list) )
{
getline(infile, tmp_gift, '\n'); //get the gift
strip_punct(tmp_gift);
add_to_existing(tmp_name, tmp_gift, list);
}
else //name is not in list
{
p_tmp.set_name(tmp_name);//set the name
getline(infile, tmp_gift, '\n'); //get the gift
strip_punct(tmp_gift);// get rid of quotes and other puncts
p_tmp.insert_gift(tmp_gift); //insert gift string into set of gifts for that person
people_iter = list.begin();//add person to list of people
list.insert(people_iter, p_tmp);
}//end else
}// end while( infile.good() )
infile.close();
}//end read_file