文件中的数字以逗号结尾:
3.0,2,3,1,2,3
2,3,4,2,3,2
4,5,6,7,4,3.0
具体代码如下:
//
// main.cpp
// Load_Data
//
// Created by tong on 2019/1/4.
// Copyright © 2019年 tong. All rights reserved.
//
#include <iostream>
typedef std::vector<std::vector<float>> Data;
typedef std::vector<float> RowData;
typedef std::vector<float> ColData;
void print(Data &data)
{
int row = data.size();
int col = data[0].size();
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
std::cout<<data[i][j]<<" ";
}
std::cout<<std::endl;
}
}
void LoadDataNum(Data &data,const char *infile)
{
std::cout<<infile<<std::endl;
std::ifstream dataFile;
dataFile.open(infile);
std::string tmpstrline;
std::string val;
RowData rowData;
if(dataFile)
{
while(!dataFile.eof())
{
getline(dataFile, tmpstrline, '\n');
std::stringstream input(tmpstrline);
if( tmpstrline != "\0")
{
while(getline(input, val, ',')) //表示以逗号结尾进行分割
{
rowData.push_back(atof(val.c_str())); //一定要用c_str()否则报错
}
data.push_back(rowData);
}
rowData.clear();
}
}
dataFile.close();
}
int main(int argc, const char * argv[]) {
// insert code here...
Data data;
char * file = "/Users/Load_Data/Load_Data/data.txt";
LoadDataNum(data, file);
print(data);
return 0;
}