无法将'const char*'转换为'std :: istream*

H'H*_*H'H 1 c++ istream

对你来说似乎很容易,但我被困在这里.这是C++中用于从ASCII文件加载矩阵的函数.

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我们从用户获取文件名,如下所示,default.dat文件可用:

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

我想知道如何使用这个filename1作为参与者的loadmatrix函数.

谢谢

Fre*_*abe 5

std::ifstream使用文件名构造一个对象,然后将指向该对象的指针传递给你的loadmatrix函数:std::ifstreaminherits std::istream,所以这个typechecks:

std::vector< std::vector<double> > matrix;
std::ifstream f( filename1 );
if ( !f ) {
    // XXX Error handling
}
loadmatrix( &f, &matrix );
Run Code Online (Sandbox Code Playgroud)