C++ (C+;+;)读取CSV文件并使用该信息创建对象(将成为链接列表)
我试图读入csv文件,然后使用读入的内容创建对象。这些对象将形成一个链接列表 当我在记事本中打开csv文件时,它看起来像这样:C++ (C+;+;)读取CSV文件并使用该信息创建对象(将成为链接列表),c++,csv,C++,Csv,我试图读入csv文件,然后使用读入的内容创建对象。这些对象将形成一个链接列表 当我在记事本中打开csv文件时,它看起来像这样: 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
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;
}
姓名、地点
鲍勃·史密斯,洛杉矶
乔·斯莫,纽约
通用名,凤凰城
我想跳过第一行(名称、位置),读入其余部分
现在,我的代码如下所示:
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;
}
ifstream文件(“File.csv”);
字符串名称、位置、skipline;
if(File.is_open())
{
//跳过第一行更好的方法?
getline(文件,skipline,,);
getline(文件、skipline);
while(File.good())
{
getline(文件名,,);
getline(文件、位置);
//创建新PersonNode(构造函数可能不需要空指针)
PersonNode*node=新PersonNode(名称、位置、nullptr、nullptr);
//测试
cout getName()我认为您不需要getline(文件,skipline,,);
来跳过第一行。
因为getline(文件,skipline);
已经跳过了第一行
发件人:
从is中提取字符并将其存储到str中,直到找到定界字符delim(或换行符“\n”,表示(2))
您需要getline(文件,skipline,,)
虽然要在循环中获取值我不明白为什么cout语句不使用std::endl
您似乎被一些C约定卡住了。而且,看起来您的链表不需要知道下一个在构建时的位置,或者在构建时的头,那么为什么构造器需要传递这些值呢d in?你可以假设下一个将是nullptr
,如果它在构建时总是这样的话。是的,我只是学习了一点关于C的知识。我有“使用名称空间std”;我不知道我可以有不止一个这样的东西。所以,如果我有“std::endl”我是否不需要使用转义符\n或者我想我不太确定它的作用。至于构造函数,我明白你的意思(我想)。那么,在创建对象之后,我会有另一行代码将其实际添加到链接列表中?我从您的代码中了解到,您正在使用名称空间std
,但这并没有解决我的注释的目的,即:为什么要使用C代码&&为什么要使对象构造复杂化?确切地说h部分是C代码?应该如何更改?(抱歉,这是一个非常新的问题)。就对象构造而言,我知道你在说什么(我想)。因此,在创建对象之后,我会有另一行代码将其添加到链接列表中?“\n”是C换行符。<代码> >代码>或<代码> EntL/<代码>(如果使用命名空间STD)是C++的端线关键字。并且<>代码> STD::cOUT/COD>可以处理字符串文字。你不必转换它们。好的捕获,谢谢。我只需要GETLIN(文件SkiPrin)。.你知道为什么我最后还是得到了额外的--Phoenix吗?嗯,我不确定,但我猜在csv文件的最末端有一个额外的换行符
,所以while(file.good())
仍然循环。你能试试这个获取行(文件,位置,'\n');
代替获取行(文件,位置)
?如果这仍然是一个额外的Phoenix,我最后的猜测是,由于location的最后一个值是Phoenix,并且在csv文件的最后有一个额外的“换行符”,while循环仍然继续,然后不知何故显示了location
的最后一个值,它是Phoenix,而name
对于unk没有输出未知原因