c++ - 无法将 ‘const char*’ 转换为‘std::istream*

标签 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();
        }
    }
}

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

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

我想知道如何将此 filename1 用作 argunemt fot loadmatrix 函数。

谢谢

最佳答案

构造一个 std::ifstream带有文件名的对象,然后将指向该对象的指针传递给您的 loadmatrix 函数:std::ifstream 继承 std::istream,所以这个类型检查:

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

关于c++ - 无法将 ‘const char*’ 转换为‘std::istream*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23078655/

相关文章:

c++ - 构建动态大小的 std::initializer_list,第二部分

c++ - 使用 RAW 指针对 boost::shared_ptr 变量进行条件初始化

java - COM 接口(interface) iStream 在哪个 DLL 中定义?

c++ - 在模板函数中从 istream 中提取 bool

c++ - 如何为布局激活 adjustsize()

c++ - 虚拟模板函数解决方法

c++ - 为什么指针访问比 vector::iterator 访问慢? (编译器代码生成)

c++ - istream 过载不起作用

c++ - 无阻塞地使用c++输入流cin

c++ - istream get 方法行为