首页 > 解决方案 > 面临迭代向量的问题> 和打印数据

问题描述

我正在读取一个 CSV 文件并将其存储在向量向量字符串中。我想打印数据,为此我使用了两个 for 循环,一个迭代向量的向量,另一个迭代向量字符串。

a1,b1,c1,d1
a1,b1,c4,d3
a1,b2,c2,d2
a2,b3,c3,d4
a2,b4,c3,d4

这是我正在阅读的 CSV 数据。下面的代码我用来打印到屏幕上

void ReadCSV::printdata(vector<vector<string>> ipd){
    for(auto it1 = ipd.begin();it1 != ipd.end();++it1){
        vector<string> test = *it1;
        for(auto it2 = test.begin();it2 != test.end();++it2){
            string r = "";
            r= *it2;
            cout<<r<<" ";
        }
        cout<<endl;
    }
}

但我得到的输出似乎没有正确迭代:

a1 b1 c1 d1 
a1 b1 c1 d1 a1 b1 c4 d3 
a1 b1 c1 d1 a1 b1 c4 d3 a1 b2 c2 d2 
a1 b1 c1 d1 a1 b1 c4 d3 a1 b2 c2 d2 a2 b3 c3 d4 
a1 b1 c1 d1 a1 b1 c4 d3 a1 b2 c2 d2 a2 b3 c3 d4 a2 b4 c3 d4

我使用下面的代码来读取数据:

vector<vector<string>> ReadCSV:: ReadData(){
    fstream fin(filename);
    vector<string> temp;
    string val1, val2, val3 ,val4;
    if(!fin.is_open()){
        cout<<"ERROR: file open";
    }
    cout<<"FIRST OUTPUT: "<<endl;
    while(fin.good()){
        getline(fin, val1,',');
        //store
        temp.push_back(val1);
        cout<<val1<<" ";
        getline(fin, val2,',');
        temp.push_back(val2);
        cout<<val2<<" ";
        getline(fin, val3,',');
        temp.push_back(val3);
        cout<<val3<<" ";
        getline(fin, val4,'\n');
        temp.push_back(val4);
        cout<<val4<<" ";
        csvdata.push_back(temp);
    }
    cout<<endl;
    return csvdata;
}

谁能告诉我哪里出错了,我面临的另一个问题是当我运行调试器(ECLIPSE IDE)并将鼠标悬停在一个变量上时,它会打开一些弹出窗口但不显示变量的值,例如“字符串 r”这个案例。谢谢

标签: c++stringvectorstleclipse-cdt

解决方案


您的 CSV 阅读器除了有一些小问题外,还被硬编码为准确读取 4 个逗号分隔值。这是一个更通用的代码,它可以读取尽可能多的行,并且每行具有可变数量的逗号分隔值。

#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>

template<typename In, typename Out>
void csv2vec(In first, In last, Out& result) {
    std::string temp;
    unsigned i{0};
    while(1) {
        do{
            if(*first == '\n') break;
            temp.push_back(*first);
            ++first;
        }while(*first != ',' && first != last);
        result[i].push_back(temp);
        if(*first == '\n') {
            ++i;
            result.resize(i+1);
        }
        temp.clear();
        if(first == last) break;
        ++first;
    }
}

int main(void) {
    std::vector<std::vector<std::string>> vec(1);
    std::ifstream in("data.txt");
    std::istreambuf_iterator<char> begin(in);
    std::istreambuf_iterator<char> end;
    csv2vec(begin,end,vec);

    for(const auto& vecouter : vec) {
        for(const auto& elem : vecouter){
            std::cout<<elem<<" ";
        }
        std::cout<<"\n";
    }
   return 0;
}

注意:我使用了 istreambuf_iterator,它从不跳过任何字符(包括空格,例如 '\n')。与跳过空格的 istream_iterator 不同,它会抓取流缓冲区中接下来的任何内容。istream_iterator 在执行格式化输入时也很有用,并且比 istreambuf_iterator 慢。参考:第 29 条,有效的 STL,Scott Meyers。


推荐阅读