这对你来说似乎很容易,但我被困在这里。这是一个 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/