C :读取csv-file被分开;和 n
C++: Read CSV-file separated by ; AND
对不起,如果这只是纯粹的愚蠢,但我遇到了通过C 的文件阅读问题。这是我想阅读的CSV数据:
5;1;0;3;3;5;5;3;3;3;3;2;3;3;0
5;1;0;3;3;5;0;3;3;3;3;2;0;0;3
5;1;1;3;3;0;0;0;0;3;5;2;3;3;3
0;3;5;5;0;2;0;3;3;0;5;1;1;0;0
0;0;3;5;5;2;0;0;0;0;5;5;1;1;0
0;0;0;0;5;2;0;0;0;0;0;5;5;1;0
;;;;;;;;;;;;;;
Code;Bezeichnung;Kosten;;;;;;;;;;;;
0;Ebene;6;;;;;;;;;;;;
1;Fluss;10; (begrenzt nutzbar);;;;;;;;;;;
2;Weg;2;;;;;;;;;;;;
3;Wald;8;;;;;;;;;;;;
4;Brücke;5;;;;;;;;;;;;
5;Felswand;12;;;;;;;;;;;;
在这里,我想读取第一个值(由;;; ;;)并将其存储在2维数组中。如果它完全被';'完全分开,那不是问题。但是如果使用
while (getline(csvread, s, ';'))
{
[...]
}
我得到这样的信息: {5}{1}{0}{3}{3}{5}{5}{3}{3}{3}{3}{2}{3}{3}{0n5}{1}
因此,它基本上保存了新线,并不认为它是定界符。
那么,即使您有两个分隔符,也可以选择使用getline吗?还是我完全离开?我还考虑过按行读取该字符串,添加a;到字符串并将其重写在文件中,以便使用getline使用;。但这不能认真是最好的选择,对吗?
您应该分别进行'n'
和';'
分开:
// here split into lines by 'n'
while (getline(csvread, line, 'n'))
{
// in here, split line by ;
std::vector<std::string> elems;
boost::split(elems, line, boost::is_any_of(";"));
// do something with elems
}
您可以使用:
的分裂函数std::vector<std::string> split(const std::string& source, const std::string& delimiter){
std::vector<std::string> result;
size_t last = 0;
size_t next = 0;
while ((next = source.find(delimiter, last)) != std::string::npos){
result.push_back(source.substr(last, next - last));
last = next + delimiter.length();
}
result.push_back(source.substr(last));
return result;
}
现在简单:
std::vector<std::vector<std::string>> parsedCSV;
while (getline(csvread, s, 'n'))
{
parsedCSV.push_back(split(s,";"));
}
我最近也必须读取CSV-DATA,然后偶然发现了相同的'问题'。这是我所做的:
- 与
getline(csvread, s)
一起阅读,这将读取到第一个newline。 - 在
;
的每一个情况下,都将字符串分开,我使用此stackoverflow答案作为拆分字符串的灵感,代码也在下面列出。
我不太在意表现,因为我只需要一次运行此程序,我不会对此解决方案的速度发表评论。
祝你好运!
编辑:显然提供了拆分字符串的代码,可能更清洁,如果要避免提升,请考虑以下代码。
#include <string>
#include <sstream>
#include <vector>
// source: https://stackoverflow.com/a/236803/4841248
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
尝试这样的东西:
std::vector<std::string> cells;
while (getline(csvread, s) ){
boost::split(cells, s, boost::is_any_of(";"));
....
}
相关文章:
- 无法逐行读取.csv文件
- 使用getline读取.csv文件时出现问题
- 读取.csv文件 c++
- 使用 fstream 读取 csv,并且只阅读 fstream
- 为什么我的getline不正确读取.csv文件
- 如何在 c++ 中跳过读取 csv 文件的第一列
- C++ 读取.csv文件,将数据放入变量中,然后放入对象中
- 如何从输入中读取 CSV 行并将每个值初始化为不同类型的变量?(C++)
- 读取.csv文件并仅使用 C++ 存储到数组中<iostream>
- Linux 与 Windows,C++读取 CSV 文件的运行时性能差异
- 读取 CSV 文件(UNICODE 编码)C++时出现编码错误
- 读取 CSV 文件
- 在C 中读取CSV文件
- 目瞪口呆地寻找一种有效的 c 和 c++ 方法来删除回车符(读取.csv文件)
- 读取CSV文件并将值存储在C 中
- 在C 中读取CSV文件中的两个列
- C :读取csv-file被分开;和 n
- C 读取CSV文件包含空单元
- 在MFC中读取.CSV文件内容
- 正在从文件中读取CSV数据