使用getLine在c++中读取CSV文件中的分隔列
Reading separated columns in a CSV file in C++ using getLine
我有一个程序,可以成功读取CSV文件。上述CSV文件是一个由3列分隔的列表。每一列每一行之间都有一个逗号。例如
第一行—艺术家,类型,歌曲第二行——迈克尔杰克逊,流行歌曲,惊悚片
等等。我想让我的程序做的是读取第一行,并将艺术家、流派和歌曲作为选项打印给用户。例如
"Choose an Option"1. 艺术家2. 类型3.首歌
然后当他们选择一个选项时,它就会显示CSV文件中的所有艺术家,歌曲或流派。
到目前为止,我有我的程序读取CSV和把每一行在一个向量。这是我到目前为止的代码…
#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<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<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;
}
我没有尝试编译任何这些函数,因为我没有环境在这里这样做。但我认为这将有助于思考方向。
现在你的数据在二维矢量,如excel表格。所以你可以通过内部向量的索引来访问
您可以创建一个std::map<string,vector<string>>
,这样您就可以将CSV文件的每一列从第2行开始存储在映射中,作为字符串向量,由CSV文件第1行列中出现的文本作为关键字。
然后,您可以通过迭代std::map
的键来表示字段的名称,这些键以字母顺序方便地存储。
读取CSV文件第一行的任务可以由您已经拥有的代码执行,或者考虑到在功能齐全的CSV文件中发现的引号字段等更复杂的代码来执行。
相关文章:
- 如何将 txt 文件中的行分隔为组件C++
- 无法通过空白将文本文件行分隔为矢量
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 读取制表符分隔的文件时出现问题 C++
- 如何更新和删除文本文件中的特定逗号分隔值?C++
- 如何将逗号分隔的文件读取为 2D int 数组?
- 读取带有分隔C++的文件
- 嵌套结构,从由空行分隔的文件中读取数据
- 如何逐行从文件中获取单词,并在C++中用分号分隔?
- 如何从文件中读取用空格分隔的数字
- 从文件中读取后,将分号分隔的整数存储到数组中
- 如何逐行读取文件并分隔行组件?
- 包含换行符分隔的单词的文件和C++中这些单词的字符串向量的大小是否相同?
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法
- C++将分隔文件导入矢量
- 如何正确创建一个由两个文件分隔的模板类
- 读取选项卡在 c++ 中将文件分隔成数组
- 读取空格将数字从文本文件分隔到整数数组 (C++)
- 读取与文件分隔的输入空间