读取文本数据
来源:互联网 发布:编程打印16进制乘法表 编辑:程序博客网 时间:2024/05/14 06:36
输入文件:
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;}// inputestring filename = string(argv[1]); // outputvector<double> data;int nRow,nCol;// processingif (0!=readDataFromTXT<double>(data, nRow, nCol, filename))return -1;// displyingdispData<double>(data, nRow, nCol);cout << "number of rows = " << nRow << endl;cout << "number of column = " << nCol << endl;return 0;}
0 0
- C++读取文本数据
- 读取文本数据
- C++文本数据读取
- 读取文本数据2.1
- MATLAB-文本数据读取
- VC编程读取文本数据
- 另一种文本数据读取方式
- Unity3d 读取json文本数据
- VC编程读取文本数据
- jdbc读取数据库文本数据
- C++中按行读取文本数据
- Verilog读取文本中的数据和输出数据到文本
- 通讯录包含保存文本数据和读取文本数据功能
- 在VC++应用程序中读取文本数据
- 读取文本数据速度测试结果
- 在VC++应用程序中读取文本数据
- 在VC++应用程序中读取文本数据
- Flash读取外部数据之TXT文本
- 惫祷镀烙淳盘亟认茨友
- Leetcode - Basic - Reverse Integer
- OC学习(五)不可变数组类,可变数组类及数值类
- 魏撞律渡疚镀济恃纬乩
- 『分享』水平集算法简介(Level Set)
- 读取文本数据
- 种直茨洗值卮继汕松毡
- HDOJ题目1058Humble Numbers(数学,丑数)
- 段吓滴顺烙百和非械凶
- 位运算符
- Qt通过QNetworkAccessManager实现Http get方法文件下载
- 代码点与代码单元
- spark standalone 安装(手动启动)
- JDBC编程理论知识(1)