0

我有一个文件包含

99,0,0,0,0,0
99,1234,0011,4314,4901,4930
e.t.c.

我想将文件读入整数的二维向量。我对 C++ 很陌生。所有行都有 x 列。行数不确定。所有值都用逗号分隔。

我可以将值读入一维向量,但我似乎无法正确获取矩阵部分。

这就是我到目前为止所拥有的;

    #include <cstdlib>
    #include <iostream>
    #include <sstream>
    #include <fstream>
    #include <string.h>
    #include <string>
    #include <vector>
    //declare data variables
    using namespace std;

    typedef vector<int> mline;
    typedef vector<mline> matrix;

    matrix sdata;
    matrix confdata;

    int writeFile();
    int readFile();


    int main ()
    {

    readFile();
    writeFile();

    }

    int writeFile ()
    {
     return 0;
    }

    int readFile()
    {
    int i = 0;
    int j = 0;
    //int k = 0;
    int spos = 0;
    int epos = 0;
    int endpos = 0;
    int slenght = 0;
    int buffersize;
    int tmpint;
    stringstream outs;
    mline tmpline;
    string filename = "sensorbase.txt";
    string tmp;
    vector<string> bufferstr;
    string delimiter = ",";
    ifstream inputFile(filename);
        string line;

        while (getline(inputFile, line))
        {
            istringstream ss(line);
                ss >> tmp;
                    bufferstr.push_back(tmp);
            i++;
    }
    buffersize = bufferstr.size();

    while(j<buffersize){
    tmpline.clear();

    endpos = bufferstr[j].rfind(delimiter);
    slenght = bufferstr[j].size();

        while (epos+1<endpos){
    if (epos!=0){spos = epos+1;}
    epos = bufferstr[j].find(delimiter, spos);

    //printf("%s",bufferstr[j].substr(spos, epos-spos).c_str());
    outs.clear();
    outs << bufferstr[j].substr(spos, epos-spos);
    outs >> tmpint;
    tmpline.push_back(tmpint);

    }
    if (slenght>endpos){
                spos = endpos+1;
                        //printf("%s",bufferstr[j].substr(spos, slenght-        endpos).c_str());
    outs.clear();
    outs << bufferstr[j].substr(spos, slenght-endpos);
    outs >> tmpint;
    tmpline.push_back(tmpint);
                }
    sdata.push_back(tmpline);
    j++;
    spos = 0;
    epos = 0;
    }

    printf("A3 %i, B5 %i",sdata[0][0],sdata[0][1]);
    return 0;
    }
4

1 回答 1

2

您可以使用std::getline分隔符,来获取每个逗号之前的整数:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

typedef std::vector<int>   mline;
typedef std::vector<mline> matrix;

int main()
{
    std::ifstream in("sensorbase.txt");
    matrix data;

    for (std::string line, number; std::getline(in, line);)
    {
        mline temp;
        std::istringstream iss(line);

        while (std::getline(iss, number, ','))
        {
            temp.push_back(std::stoi(number));
        }

        data.push_back(temp);
    }
}
于 2013-10-23T20:36:05.047 回答