问题
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