gpt4 book ai didi

c++ - 使用 getLine 在 C++ 中读取 CSV 文件中的分隔列

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

我有一个可以成功读取 CSV 文件的程序。所述CSV文件是一个由3列分隔的列表。每列之间每行之间都有一个逗号。例如

第 1 行 --- 艺术家、流派、歌曲第 2 行 --- 迈克尔 jackson ,流行音乐,惊悚片

等等。我想让我的程序做的是读取第一行并获取艺术家、流派和歌曲,将它们作为选项打印给用户。例如

“选择一个选项”1. 艺术家2. 流派3.歌曲

然后当他们选择一个选项时,它会向他们显示 CSV 文件中的所有艺术家、歌曲或流派。

到目前为止,我的程序读取 CSV 并将每一行放入一个 vector 中。到目前为止,这是我的代码......

#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
ifstream infile("music_list.csv");
string line = "";
vector<string> all_words;
cout << "Hello";
while (getline(infile, line))
{
stringstream strstr(line);
string word = "";
while (getline(strstr,word, ','))
{
all_words.push_back(word);
}

for (unsigned i = 0; i < all_words.size(); i++)
{
cout << all_words.at(i)<< "\n";
}

}
system("pause");
return 0;
}

我只是无法弄清楚如何让它读取第一行,将第一行中已经用逗号分隔的每个字符串分开,然后将其作为选项输出给用户。所以本质上,我可以将艺术家、流派、歌曲更改为 CSV 文件中的开胃菜、菜肴、饮料等内容。

最佳答案

首先您必须读取 csv 文件并将行存储在 vector 中,您可以使用此函数来执行此操作。

vector<string> readCsvFileContent(const string file)
{
vector<string> buffer;
ifstream configFile;
configFile.exceptions(ifstream::badbit);
try
{
configFile.open(file.c_str(),ifstream::in);
if(configFile.is_open())
{
string line;
while (getline(configFile,line))
{
buffer.push_back(line);
}
configFile.close();
}
}
catch (ifstream::failure e){
throw e;
}
return buffer;
}

然后将每一行条目拆分为 2D vector 。为此,您可以使用此功能

vector<vector<string>> processCsvList(vector<string> csvList)
{
#define SINGER_CONFIG_COUNT 3 //number of comma separated data suppose to be in one line.
#define DELIMITED_CHAR ","
#define EMPTY_STRING "";

vector<vector<string>> tempList;
string configCell ="";
for(vector<string>::iterator it = csvList.begin(); it != csvList.end(); ++it)
{
if(*it == EMPTY_STRING)
{
continue;
}
stringstream configLine(*it);
vector<string> tempDevice;
for(int i=0; i<SINGER_CONFIG_COUNT; i++)
{
if(getline(configLine,configCell,DELIMITED_CHAR))
{
tempDevice.push_back(configCell);
}else
{
tempDevice.push_back(EMPTY_STRING);
}
}
tempList.push_back(tempDevice);
}
return tempList;
}

我没有尝试编译这些函数中的任何一个,因为我这里没有这样做的环境。但我认为这将有助于思考方向。

现在您的数据在 2D vector 中,例如 Excel 工作表。所以你可以通过内部 vector 的索引访问。

关于c++ - 使用 getLine 在 C++ 中读取 CSV 文件中的分隔列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15870897/

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