无法输出链接列表的内容
Can not output content of the linked list
我想用文本文件的内容填充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
我决定在这里停下来测试一下所做的工作,所以我在主菜单中调用了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
变量有关?(但我不知道是什么,因为我没有经验。
你能告诉我我做错了什么吗?
您需要一个缓冲区来读取。您所做的是创建长度为1字节的lastName
字符串,并向其中读取最多maxTextLength
字节。
//create temporary buffers
char* buffFirstName = new char[maxTextLength];
char* buffLastName = new char[maxTextLength];
while( !g.eof() )
{
//read into temporary buffers
g.getline( &buffFirstName[0], maxTextLength, delim );
g.getline( &buffLastName[0], maxTextLength, delim );
//create person data
Person p(buffFirstName, buffLastName);
// add it to the list
persons.push_back(p);
}
//release the buffers
delete[] buffFirstName;
delete[] buffLastName;
Person( const char *lName = "", const char *fName = "" )
{
lastName += lName;
firstName += fName;
}
不确定,但在c++中,你能用这个作为参数吗?:
const char *lName = ""
我理解您想要什么(默认值(,但它将值设置为"。尝试不使用它。
相关文章:
- 从链接列表c++中删除一个项目
- 读取文件的最后一行并输入到链接列表时出错
- 下面是我为检测链接列表中的循环而制作的代码
- 有人能帮我处理这个链接列表吗?C++
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 链接列表运算符重载没有打印出我想要的内容
- 链接列表在 cpp 中包含不同的对象类
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 如何在构建链接列表时调整头、尾指针
- Shared_ptr双链接列表内存泄漏
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 在链接列表中查找元素 - C++
- 删除链接列表中剩余的最后一个节点
- 只有我的"链接列表"中的第一个节点正在打印
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 将元素插入链接列表