【发布时间】:2014-05-23 12:36:55
【问题描述】:
我想用文本文件的内容填充linked list。
为了实现这一点,我创建了一个结构,该结构将保存文件中一行的数据。
然后我会简单地浏览文件中的行,并在链接的list 中添加填充的结构。
我似乎已经成功地填充了列表,但我无法显示其内容。
这是我目前所拥有的:
Person.h
#ifndef _Person_h_
#define _Person_h_
#include <iostream>
#include <list>
#include <fstream>
#include <string>
class Lista
{
private:
struct Person
{
std::string lastName;
std::string firstName;
// other fields ommited for brewity
Person( const char *lName = "", const char *fName = "" )
{
lastName += lName;
firstName += fName;
}
~Person()
{
lastName.clear();
firstName.clear();
}
};
// my linked list of Persons
std::list<Person> persons;
public:
// data comes from a comma delimited file
Lista( const char *inputFile, int maxTextLength = 100, char delim = ',' )
{
std::ifstream g;
g.open(inputFile);
if( g.is_open() )
{
std::string temp( maxTextLength, 0 );
while( !g.eof() )
{
Person p;
// fill Person structure
g.getline( &p.lastName[0], maxTextLength, delim );
g.getline( &p.firstName[0], maxTextLength, delim );
// add it to the list
persons.push_back(p);
}
g.close();
}
}
// testing function- > it should just display the content of the list
void print()const
{
std::list<Person>::const_iterator it;
for( it = persons.begin(); it != persons.end(); ++it )
{
std::cout << "L: " << it->lastName.c_str() << std::endl
<< "F: " << it->firstName.c_str() << std::endl << std::endl;
}
}
// emty list
~Lista(){ persons.clear(); }
};
#endif
我决定在这里停下来测试一下做了什么,所以我在我的 main 中调用了print() 函数:
main.cpp
#include "Person.h"
int main()
{
Lista p( "test comma separated file.txt", 100, ',' );
p.print();
return 0;
}
编译器没有报告错误,但是当我运行我的测试程序时,我得到了这个:
L:
F:
L:
F:
Press any key to continue...
如果我在Lista 构造函数中添加cout,它会正确输出名称。似乎我在构造函数中做错了什么(也许它与临时的Person 变量在堆栈上有关?)但我不知道是什么,因为我没有经验。
你能告诉我我做错了什么吗?
【问题讨论】:
标签: c++ stl linked-list