gpt4 book ai didi

c++ - (C++) 读取 CSV 文件并使用信息创建对象(这将成为一个链表)

转载 作者:太空宇宙 更新时间:2023-11-04 11:37:36 25 4
gpt4 key购买 nike

我正在尝试读入一个 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;
}

这在文件中的大部分内容似乎都可以读取,但是有没有更好的方法来跳过第一行?此外,当文件被打印出来时,最后一列的第二行被复制,所以它看起来像这样:

输入:

姓名、地点鲍勃·史密斯,洛杉矶乔·斯莫,纽约通用名,凤凰

输出是:

鲍勃·史密斯 --- 洛杉矶乔·斯莫——纽约通用名---凤凰---凤凰

如果相关,对象的构造函数如下所示(将使用 OtherNode,因为将涉及另一个链表,但我还不担心)。

PersonNode::PersonNode(string name, string location, Node *next, OtherNode *head) {
PersonNode::name = name;
PersonNode::location = 位置;
人节点::下一个=下一个;
PersonNode::OtherNode = OtherNode;
}

感谢您的帮助,非常感谢。

最佳答案

我认为您不需要 getline(File, skipline, ','); 来跳过第一行。因为 getline(File, skipline); 已经跳过了第一行

来自 (documentation) :

(1) istream& getline (istream& is, string& str, char delim);
(2) istream& getline (istream& is, string& str);

从 is 中提取字符并将它们存储到 str 中,直到找到定界字符 delim(或换行符,'\n',对于 (2))。

你需要 getline(File, skipline, ','); 来获取循环中的值

关于c++ - (C++) 读取 CSV 文件并使用信息创建对象(这将成为一个链表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22570060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com