C ++:读取CSV文件,由; AND \ n [英] C++: Read CSV-file separated by ; AND \n

查看:114
本文介绍了C ++:读取CSV文件,由; AND \ n的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,如果它只是纯粹的愚蠢,但我遇到一个文件读取问题通过C ++。
这是我想要阅读的CSV数据:

Sorry if it's just pure stupidity but I'm stuck at a file reading problem via C++. This is the CSV data that I'd like to read:

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维数组中。如果它完全由';'分隔,这不会是一个问题。但是如果使用

here, I'd like to read the first values (separated by ;;;;) and store it in a 2 dimensional array. Which would not be a problem if it was seperated completely by ';'. But if use

while (getline(csvread, s, ';'))
{
[...]
}



我得到这样的信息: {5} {1} {0} {3} {3} {5} {5} {3} {3} {3} {3} {2} {3} {3} {0\\\
5} {1 }

I get information like this: {5}{1}{0}{3}{3}{5}{5}{3}{3}{3}{3}{2}{3}{3}{0\n5}{1} so it basically saves the newline and does not think of it as delimitator.

因此,有一个选项可以使用getline即使你有两个分隔符?还是我完全关闭?
我也想过一行一行读一个字符串,添加一个;到字符串并重写它在一个文件,以便重用getline使用;。

So is there an option to use getline even if you have two delimitators? Or am I completely off? I also thought about reading it line by line to a string, adding a ; to the string and rewriting it in a file in order to reuse getline using ;. But this can't seriously be the best option, right?

推荐答案

你可以使用一个分割函数:

you can use a splitting function like :

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,";"));
}

这篇关于C ++:读取CSV文件,由; AND \ n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆