Best Ways to Trim a string in C++ [stackoverflow]
Using OpenCV with gcc and CMake

c++文件操作——输入文件包含矩阵形式的数据,输出为vector

Author posted @ 2013年2月19日 14:20 in C/C++ , 3005 阅读

方法一:来自网络,推荐此法,直接使用标准库。简洁好用

#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
typedef vector<vector<int> > Mat;

Mat input();
int main (void)
{
       Mat a = input();
       for (int i = 0; i < a.size();i++)
      {
            for(int j = 0; j < a[i].size();j++)
           {
                 cout<<a[i][j]<<" "<<flush;
           }
           cout<<endl;
      }
     return 0;
}

Mat input()
{
       ifstream in("int.txt");
       Mat a;
       istringstream istr;
       string str;
       vector<int> tmpvec;
       while(getline(in,str))
      {
           istr.str(str);
           int tmp;
           while(istr>>tmp)
          {
               tmpvec.push_back(tmp);
          }
         a.push_back(tmpvec);
         tmpvec.clear();
         istr.clear();
      }
    in.close();
   return a;
}

方法二见原链接:http://hi.baidu.com/walanlixuming/item/63324ae80cdeccaece2d4ff4

稍作改动,写成两个函数如下方便调用:

#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <fstream>
#include <stdlib.h>
//#include <boost/algorithm/string.hpp>

using namespace std;
//using namespace boost::algorithm;
typedef vector<vector<double> > Mat;

/* fileName should be of string type */
Mat inputMat(string & fileName){
  ifstream infile;
  infile.open(fileName.c_str());
  Mat a;
  istringstream istr;
  string str;
  vector<double> tempvec;
  while(getline(infile, str)){
    istr.str(str);
    double tmp;
    while(istr>>tmp){
      tempvec.push_back(tmp);
    }
    a.push_back(tempvec);
    tempvec.clear();
    istr.clear();
  }
  infile.close();
  return a;
}

void showMat(Mat M){
  for(int i=0; i<int(M.size()); i++){
    for(int j=0; j<int(M.at(i).size()); j++){
      cout<<M.at(i).at(j)<<" "<<flush;
    }
    cout<<endl;
  }
  
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter