输入文件:
1 2 3
4 5 6
输出到vector中
代码:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <cassert>
using namespace std;
template<typename DT>
bool checkLineData(istringstream &instr, const int &nCol)
{
int c = 0;
DT tpVar;
while(instr>>tpVar)
{
c++;
}
instr.clear();
instr.seekg(istringstream::beg);
return (c==nCol);
}
template<typename DT>
void dispData(vector<DT> &data, const int &nRow, const int &nCol)
{
int index = 0;
int r,c;
int nColM1 = nCol-1;
assert((int)(data.size())==(nRow*nCol));
for (r = 0; r < nRow; r++){
for (c = 0; c < nColM1; c++){
cout << data[index] << "\t";
index++;
}
cout << data[index];
index++;
cout << endl;
}
}
template<typename DT>
int readDataFromTXT(vector<DT> &data,int &nRow, int &nCol, const string &filename)
{
ifstream infile;
istringstream instr;
string line; // the string to store one line.
DT tpVar;
int k;
infile.open(filename.c_str(), ios_base::in);
if (!infile.is_open())
{
cerr << "failed to open the file of " << filename << "." << endl;
return -1;
}
// read the first line and check number of column.
std::getline(infile, line);
instr.str(line);
nCol = 0;
while(instr >> tpVar) {
nCol++;
}
// read the remaining data and stored into a vector.
infile.seekg(ifstream::beg);
nRow = 0;
while(!infile.eof())
{
std::getline(infile, line); // get one line.
instr.clear(); // Clears the stream error state flags by assigning them the value of state.
instr.str(line); // ready to read the data.
if (checkLineData<DT>(instr, nCol))
{
for (k = 0; k < nCol; k++)
{
instr >> tpVar;
data.push_back(tpVar);
}
nRow++;
}
}
infile.close();
return 0;
}
int main(int argc, char **argv)
{
if (argc != 2)
{
cerr << "[ ERROR ] error using current application." << endl;
cerr << "[ HELP ] using it in the following way:" << endl;
cerr << "[ HELP ] ./main.exe filename.txt" << endl;
return -1;
}
// inpute
string filename = string(argv[1]);
// output
vector<double> data;
int nRow,nCol;
// processing
if (0!=readDataFromTXT<double>(data, nRow, nCol, filename))
return -1;
// displying
dispData<double>(data, nRow, nCol);
cout << "number of rows = " << nRow << endl;
cout << "number of column = " << nCol << endl;
return 0;
}