How do I stream a file into a matrix in C++ boost ublas?

↘锁芯ラ 提交于 2019-12-23 05:29:22

问题


I'm trying to read in a file that contains matrix data into a boost matrix. "" is already supposed to have operator overloads for this sort of thing and I can get it to write to a standard stream (cout). I don't know what's wrong with going the other way. I'm fairly new to C++, so I'm guessing I'm making an incorrect assumption regarding file streams, but it seemed like it made sense. Here are the web pages I'm going on:

http://www.boost.org/doc/libs/1_51_0/boost/numeric/ublas/io.hpp

http://www.cplusplus.com/reference/iostream/ifstream/ifstream/

Here's my code:

using namespace std;
matrix<double> M;
ifstream s("C:\temp\perm.txt", ifstream::in);

s >> M;
s.close();

std::cout << M;

Here's what my file looks like:

[4,4]((0,0,1,0),(0,0,0,1),(0,1,0,0),(1,0,0,0))

回答1:


Here is a small example, please try it out and see what happens. If this doesn't work, I suspect that the problem is that the file path is wrong or the program is failing to read from the text file:

#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <iostream>
#include <fstream>

int main()
{
    boost::numeric::ublas::matrix<double> m;
    std::ifstream s("C:\temp\perm.txt");
    if (!s)
    {
        std::cout << "Failed to open file" << std::endl;
        return 1;
    }
    if (!s >> m)
    {
        std::cout << "Failed to write to matrix" << std::endl;
        return 1;
    }
    std::cout << "Printing matrix: ";
    std::cout << m;
}


来源:https://stackoverflow.com/questions/12450753/how-do-i-stream-a-file-into-a-matrix-in-c-boost-ublas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!