(c++)读取CSV文件并使用信息创建对象(这将成为一个链表)
(C++) Reading in a CSV file and creating objects with the information (that will become a linked list)
我试图在csv文件中读取,然后使用读取的内容来创建对象。这些对象将形成一个链表。
当我在记事本中打开csv文件时,它看起来像这样:
名称、位置鲍勃·史密斯,洛杉矶乔·斯莫,纽约通用名称,凤凰
我想跳过第一行(Name,Location)并读取其余部分。
现在我的代码是这样的:
ifstream File("File.csv");
string name, location, skipline;
if(File.is_open())
{
//Better way to skip the first line?
getline(File, skipline, ',');
getline(File, skipline);
while (File.good())
{
getline(File, name, ',');
getline(File, location);
//Create new PersonNode (May not need the null pointers for constructor)
PersonNode *node = new PersonNode(name, location, nullptr, nullptr);
//Testing
cout << node->getName() << " --- " << node->getLocation() << endl;
//Add HubNode to linked list of Hubs (global variable hubHead)
node->setNext(hubHead);
hubHead = node;
}
}
else
{
cout << "Error Message!" << endl;
}
在大多数情况下,这似乎可以在文件中读取,但是是否有更好的方法跳过第一行?另外,当输出文件时,最后一列的第二行被复制,看起来像这样:
输入:名称、位置鲍勃·史密斯,洛杉矶乔·斯莫,纽约通用名称,凤凰
输出为:
Bob Smith—Los Angeles乔·斯莫——纽约通用名——凤凰——凤凰
如果它是相关的,对象的构造函数看起来像这样(OtherNode将被使用,因为另一个链表将涉及,但我还不担心)。
PersonNode::PersonNode(string name, string location, Node *next, OtherNode *head) {
PersonNode::name = name;
PersonNode::location = location;
PersonNode::next = next;
PersonNode::OtherNode = OtherNode;
}
谢谢你的帮助,我非常感激。
我不认为你需要getline(File, skipline, ',');
跳过第一行。因为getline(File, skipline);
已经跳过了第一行
(1) istream& getline (istream& is, string& str, char delim);
(2) istream& getline (istream& is, string& str);
从is中提取字符并将其存储到str中,直到找到分隔字符delim(或者对于(2)找到换行字符'n')。
您需要getline(File, skipline, ',');
虽然在循环中获取值
- 链表,将列表复制到另一个列表
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 如何在 c++ 中比较 2 个链表并将匹配的数据放入另一个链表中
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 仅显示链表的最后一个元素
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 创建了一个链表,但如何删除 c++ 中的"所有"节点
- 在C++的链表末尾插入一个节点
- 在解决链表问题时创建一个额外的节点是一个好习惯吗?
- 插入一个基本的单向链表节点似乎破坏了我的 c++ 代码?
- C++:如何做一个链表,结构作为参数传递?
- 程序的输出不是来的,它是一个链表程序
- 如果我们不创建一个新节点并使用指针插入数据并建立链接(在链表中)怎么办?
- 链表指针赋值为什么我们不能直接将尾巴分配给 temp 而不是尾巴>尾巴下一个
- 你能在链表中有一个动态数组和它的内存分配吗
- 如何编写一个类似于kernellist_head的c++风格的双链表实现
- 为什么T是未定义的?我正在尝试实现一个用于双链表的节点类,它不喜欢我使用友元运算符后的T
- C++链表最后一个元素的迭代器?
- C++ 链表程序打印最后一个数据项 n 次
- 在 "CodePad" 中执行链表操作时转储的核心(这是一个在线C++编译器)