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

(C++) Reading in a CSV file and creating objects with the information (that will become a linked list)

本文关键字:链表 一个 信息 CSV 读取 c++ 文件 创建对象      更新时间:2023-10-16

我试图在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, ',');虽然在循环中获取值

相关文章: