将字符串转换为2d数组

时间:2013-09-05 16:52:54

标签: c++

我有一个输入文件,其中第一列是字符串,其余是数值。

E2   1880    1   0   67.50   10.50   -1.00   -1.00
E2   1880    1   4   66.50   11.50   -1.00   -1.00
E2   1880    1   8   66.50   11.50   -1.00   -1.00
E2   1880    1   12      65.50   11.50   -1.00   -1.00
E2   1880    1   16      64.50   11.50   -1.00   -1.00
E2   1880    1   20      63.50   12.50   -1.00   -1.00
E2   1880    2   0   63.50   12.50   -1.00   -1.00
E2   1880    2   4   62.50   12.50   -1.00   -1.00
E2   1880    2   8   62.50   12.50   -1.00   -1.00

问题是我需要将输入文件存储在2d数组中但是当我尝试这样做时我只得到0并且我怀疑它是因为在第一列中没有数值..

这里是代码

sprintf(FILE,"test.dat");
IN.open(FILE,ios::in);
if(IN.is_open()){
    while ( IN.good() ) {
        getline (IN,line);
        ++data;
    }   
    data -= 1;
}
IN.clear();
IN.close();

double** buf;
buf = new double* [data];
for(int k=0;k<data;k++) buf[k] = new double[COL];
for(int k=0;k<data;k++){
    for(int j=0;j<COL;j++) buf[k][j] = 0.;
} 

sprintf(FILE,"test.dat");
IN.open(FILE,ios::in);
if(IN.is_open()){   
for(int j=0;j<data;j++){
    for(int k=0;k<COL;k++){ 
        IN >> buf[j][k];    
    }
}
IN.clear();
IN.close();

非常感谢!

3 个答案:

答案 0 :(得分:2)

#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;

int main()
{
    vector<vector<double>> data;
    ifstream file("test.dat");
    string line;
    while (getline(file, line))
    {
        data.push_back(vector<double>());
        stringstream ss(line);
        // skip first column
        { string temp; ss >> temp; }
        double value;
        while (ss >> value)
        {
            data.back().push_back(value);
        }
    }

    for (int y = 0; y < data.size(); y++)
    {
        for (int x = 0; x < data[y].size(); x++)
        {
            cout << data[y][x] << " ";
        }
    }
    cout << endl;
}

答案 1 :(得分:1)

首先,这只会保存line

中的最后一行
while ( IN.good() ) {
    getline (IN,line);
    ++data;
} 

我认为这不是你想要的。

为了存储数组中文件的数据,只需使用

int j = 0;
int k = 0;
std::string discard;
IN >> discard; // discard first "E2"
while (IN >> buf[k][j]){
     if (j < COL-1) j++;
     else if (k < data){  // whenever j reaches COL - 1
         IN >> discard;   // next element (which is "E2" is discarded)
         j = 0;           // col nr reseted
         k++;             // row nr incremeted
     }
}

此代码假定不包含“E2”的列。

答案 2 :(得分:0)

您的while循环应更改为:

while ( std::getline(IN, line) )
相关问题