Last active
December 10, 2015 22:18
-
-
Save xuhdev/4500925 to your computer and use it in GitHub Desktop.
Load matrix from an ascii file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 2 3 4 | |
9 8 7 6 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <istream> | |
#include <string> | |
#include <sstream> | |
#include <vector> | |
// load matrix from an ascii text file. | |
void load_matrix(std::istream* is, | |
std::vector< std::vector<double> >* matrix, | |
const std::string& delim = " \t") | |
{ | |
using namespace std; | |
string line; | |
string strnum; | |
// clear first | |
matrix->clear(); | |
// parse line by line | |
while (getline(*is, line)) | |
{ | |
matrix->push_back(vector<double>()); | |
for (string::const_iterator i = line.begin(); i != line.end(); ++ i) | |
{ | |
// If i is not a delim, then append it to strnum | |
if (delim.find(*i) == string::npos) | |
{ | |
strnum += *i; | |
if (i + 1 != line.end()) // If it's the last char, do not continue | |
continue; | |
} | |
// if strnum is still empty, it means the previous char is also a | |
// delim (several delims appear together). Ignore this char. | |
if (strnum.empty()) | |
continue; | |
// If we reach here, we got a number. Convert it to double. | |
double number; | |
istringstream(strnum) >> number; | |
matrix->back().push_back(number); | |
strnum.clear(); | |
} | |
} | |
} | |
// example | |
#include <fstream> | |
#include <iostream> | |
int main() | |
{ | |
using namespace std; | |
// read the file | |
std::ifstream is("input.txt"); | |
// load the matrix | |
std::vector< std::vector<double> > matrix; | |
load_matrix(&is, &matrix); | |
// print out the matrix | |
cout << "The matrix is:" << endl; | |
for (std::vector< std::vector<double> >::const_iterator it = matrix.begin(); it != matrix.end(); ++ it) | |
{ | |
for (std::vector<double>::const_iterator itit = it->begin(); itit != it->end(); ++ itit) | |
cout << *itit << '\t'; | |
cout << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment