将字符串转换为二维数组

Convert string to 2d array

本文关键字:二维数组 转换 字符串      更新时间:2023-10-16

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

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();

非常感谢!

#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;
}

首先,这将只保存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"的列。

您的while循环应更改为:

while ( std::getline(IN, line) )