c++ Linux ifstream读取CSV文件
c++ linux ifstream read csv file
void Lexicon::buildMapFromFile(string filename ) //map
{
ifstream file;
file.open(filename.c_str() );
string wow, mem, key;
unsigned int x = 0;
while(true) {
getline(file, wow);
if (file.fail()) break; //check for error
while (x < wow.length() ) {
if (wow[x] == ',') {
key = mem;
mem.clear();
x++; //step over ','
} else
mem += wow[x++];
}
list_map0.put(key, mem); //char to string
list_map1.put(mem, key); //string to char
mem.clear(); //reset memory
x = 0;//reset index
}
file.close();
}
这个函数读取一个两列的csv文件,并创建一个以column1为键的column2的映射。我用g++编译,文件在大学文件共享中,当我用。/foo运行程序时,csv文件[在与foo相同的目录文件夹中]没有被读取…为什么?
可能您没有读取该文件的权限。执行命令ls -l <csv_file>
看看你是否有权阅读。有关文件权限的更多信息,请参阅此链接https://help.ubuntu.com/community/FilePermissions
试试下面的代码对我来说是完美的
#include <iostream>
#include <stdio.h>
#include <map>
#include <string>
#include <fstream>
using namespace std;
int main(void ) //map
{
map<string, string> list_map0;
map<string, string> list_map1;
string filename = "csv";
ifstream file;
file.open(filename.c_str() );
string wow, mem, key;
unsigned int x = 0;
while(true) {
getline(file, wow);
if (file.fail()) break; //check for error
while (x < wow.length() ) {
if (wow[x] == ',') {
key = mem;
mem.clear();
x++; //step over ','
} else
mem += wow[x++];
}
list_map0[key] = mem; //char to string
list_map1[mem] = key; //string to char
mem.clear(); //reset memory
x = 0;//reset index
}
printf("%dn", list_map0.size());
file.close();
}
相关文章:
- 正在将csv文件读取为双精度矢量
- 如何选择在 csv 文件中输出的位置
- 有没有办法在不使用 getline() 的情况下从.csv文件中读取?
- 无法读取C++中的 CSV 文件
- 流:CSV 文件中的换行符
- 如何正确格式化csv文件?
- 正在分析CSV文件-C++
- 如何获取组件和搜索 CSV 文件
- C++ 中的 CSV 文件管理(特别是设置标头和每个标头将分别具有的值)
- 无法逐行读取.csv文件
- 非常快速地阅读 CSV 文件
- 该程序将.csv文件中的一系列单词放入数组中,然后随机生成句子.但它不起作用
- CSV文件之间的差异,使用getline()产生不同的结果
- 将 CSV 文件中的双倍值C++到矢量中
- C++ 将 CSV 文件的列写入向量
- 使用getline读取.csv文件时出现问题
- CSV文件未从缓冲区获取数据
- 错误的值是使用c++从CSV文件数据写入数组
- 将csv文件加载到MySQL C++中
- 读取C++中的大型CSV文件(~4GB)