从C C文件读取矩阵++ [英] read matrix from a file in C C++

查看:352
本文介绍了从C C文件读取矩阵++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道,对于存储在文件中,因为它是一个矩阵,即:该文件是各种元素之间用空格(S)分开矩阵的行中的每一行,我怎么能predetermine的大小矩阵,然后创建一个同样大小的数组,并读入C和C ++的数组?如果你有一些code的例子,这将是AP preciated!

Just wonder, for a matrix stored in a file as what it is, i.e. each line in the file being a row of the matrix where elements are separated by space(s), how can I predetermine the size of the matrix, then create an array of the same size and read it into the array in C and C++? If you have some code example, that would be appreciated!

感谢和问候!

推荐答案

这样的事情。您需要包括矢量,sstream和字符串。

Something like this. You need to include vector, sstream and string.

有没有必要找出向量的大小预先

There is no need to find out the size of the vector in advance.

std::vector<int> readRow(std::string row) {
  std::vector<int> retval;
  std::istringstream is(row);
  int num;
  while (is >> num) retval.push_back(num);
  return retval;
}

std::vector<std::vector<int> > readVector(std::istream &is) {
  std::string line;
  std::vector<std::vector<int> > retval;
  while (std::getline(is, line))
    retval.push_back(readRow(line));
  return retval;
}

这篇关于从C C文件读取矩阵++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆