c++ - 将字符串转换为二维数组

标签 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

问题是我需要将输入文件存储在二维数组中,但是当我尝试这样做时,我只得到 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;
}

关于c++ - 将字符串转换为二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18641891/

相关文章:

c++ - 如何在 C++ 中使 2 个文件指针顺序写入一个文件?

c++ - 如何等待文件存在(并被释放)?

C++0x 右值引用 - 左值-右值绑定(bind)

c++ - 包含包含 stb_image.h 的文件时出现重复符号错误

c++ - 奇怪的 gcc 错误 : stray '\NNN' in program

c++ - 将数组传递给 C++ 中的函数? [彩票号码]

c++ - floor() 行为异常

c++ - 无法锁定 Qt 互斥锁 (QReadWriteLock) 访问冲突写入

C++ 库组织

c++ - sprintf 和 char [] 与字符串