Question

It seems to be easy for you, but I am stuck here. Here is a function in C++ for loading matrix from ASCII 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 we i is not a delim, then append it to strnum
            if (delim.find(*i) == string::npos)
            {
                strnum += *i;
                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();
        }
    }
}

In the code I have, we get file name from user as below there is default.dat file availble:

const char* filename1 = (argc > 1) ? argv[1] : "default.dat";

I am wondering how I can use this filename1 as argunemt fot loadmatrix function.

Thanks

Was it helpful?

Solution

Construct a std::ifstream object with the file name, and then pass a pointer to that object to your loadmatrix function: std::ifstream inherits std::istream, so this typechecks:

std::vector< std::vector<double> > matrix;
std::ifstream f( filename1 );
if ( !f ) {
    // XXX Error handling
}
loadmatrix( &f, &matrix );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top