正在从文件中读取中的数据并插入到链表C++中
Reading data in from file and inserting into Linked List C++
对于这个程序,我必须从txt文件中读取一个名称列表,并为每个名称创建一个新节点,然后将节点插入到链表中,并在读取新名称时对其进行排序。我很难逐行正确读取文件,创建新节点并将数据放入。我对链表很陌生,但是在我的插入函数中,逻辑似乎是合理的,我认为我的错误是由我的语法引起的。这是我到目前为止的主要内容:
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include "SortedLinkList.h"
using namespace std;
int main()
{
SortedLinkList<string> sll; //create sortedlinklist object
SortedLinkList<string> sll2;
ifstream infile("List1.txt");
if(infile.fail()) {
cout << "the input file could not be opened" << endl;
exit(0);
}
else {
cout << "Opening file 1" << endl;
string s;
while (infile >> s)
{
infile >> sll;
sll.insert(s); //attempting to create new node and use data read
from file
}
}
}
这是我的插入函数。在"SortedLinkList.h"中该类是模板化的,并且已经提供了Node.h类,它已经具有getData()和getNext()函数。变量current、head、previor和count都已声明。"node.h"文件#包含在"SortedLinkList.h"中。
template <class T>
void SortedLinkList<T>::insert(const T & value)
{
cout << "insert data" << endl;
//allocate a node with new
Node<T> *newNode, *current, *previous;
newNode = new Node<T>(value);
current = head;
previous = 0;
while(current != NULL)
if(head == 0)
{
head = newNode;
}
else
{
SortedLinkList* current = head;
SortedLinkList* previous = 0;
//traverse list to find ins. location
while(current != 0)
{
if(current->getData() >= newNode->getData())
{
break;
}
else
{
previous = current;
current = current->getNext();
}
}
//insert at head
if(current == head)
{
newNode->getNext() = head;
head = newNode;
}
//insert after head
else
{
newNode->getNext() = current;
previous->getNext() = newNode;
}
}
count++;
}
以下几行看起来像是错误地添加了类型SortedLinkList*
。
SortedLinkList* current = head;
SortedLinkList* previous = 0;
在函数的开头已经有了current
和previous
的声明:
Node<T> *newNode, *current, *previous;
也许你打算使用:
current = head;
previous = 0;
您发布的错误对应于以下行:
infile >> sll;
看看你在做什么,你可以去掉那条线。
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 预处理器:插入结构名称中的前一个行号
- 在未初始化映射的情况下,将值插入到映射的映射中
- 如何在c++中只将键插入到bimap的一侧
- 如何将结构插入到集合中并打印集合的成员
- C++json插入数组
- Visual Studio 2019:插入多个C++风格的单行注释
- nlohmann-json将一个数组插入到另一个数组中
- 有效地使用std::unordered_map来插入或增加键的值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 正在插入动态数组
- 插入或删除时获取usb的dos_name
- 叮叮当当在修复时插入多个"覆盖"说明符
- 链表c++插入,所有情况都已检查,但没有任何工作
- 将重物插入std::map
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 在数字之间插入 + 或 - 符号以使其等于整数
- 在字符串中插入空格
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?