在C ++中输入.csv数据(浮点数和字符串)矩阵

时间:2014-10-01 12:02:47

标签: c++ csv input

我编写了以下C ++输入函数。它需要一个.CVS文件并返回一个矩阵(类型vector < vector< double>>)。它仅适用于.CSV文件中的数值,因为它将值作为c字符串,atof()函数将它们转换为float。

我想改变这个功能并改进它,这样它不仅可以输入数字数据,还可以输入数字和字符串,无论列或行包含什么样的数据。

知道如何做到这一点?提前谢谢!。

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

typedef vector<double> Vector;
typedef vector<Vector> Matrix;

Matrix input(string& file_name) {
    string line;
    Matrix M;

    do {
        cout << "Enter the name of a .csv file: ";
        cin >> file_name;
        string data("./path/" + file_name + ".csv");
        ifstream file(data);

        if (file.is_open()) {
            while (getline(file, line)) {
                Vector ROW;
                istringstream iss(line);
                string value;
                while (getline(iss, value, ',')) {
                    /* HERE I TAKE THE VALUES OF THE .CSV MATRIX AS C-STRINGS
                       AND CONVERT THEM AS FLOATS                          */
                    ROW.push_back(atof(value.c_str()));
                }
                M.push_back(ROW);
            }
            file.close();
        } else {
            cout << endl << "Error: Incorrect name or unable to open the file."
                 << endl;
        }
    } while (M.empty());

    return M;
}

int main() {
    string name = "test";
    Matrix data;
    data = input(name);

    /* Print the matrix*/
    for (size_t i(0); i < data.size(); ++i) {
        for (size_t j(0); j < data[i].size(); ++j) {
            cout << data[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

1 个答案:

答案 0 :(得分:0)

您的第一个问题是定义可以存储任何类型值的容器:

typedef struct {
  double fValue;
  std::string sValue;
  enum value_tag {type_string, type_float};
  value_tag type;
} CvsValue;

std::vector<std::vector<CvsValue> > Matrix;

然后,您可以解析CSV值并以适当的格式存储。我建议将逻辑封装在CvsValue构造函数中。