在我的项目中,我需要使用以下库(OMPL) . 我特别感兴趣的是成员函数printAsMatrix(std :: ofstream&out),它将数据输出到终端或文件 . 这里function:
void ompl::geometric::PathGeometric::printAsMatrix(std::ostream &out) const
{
const base::StateSpace* space(si_->getStateSpace().get());
std::vector<double> reals;
for (unsigned int i = 0 ; i < states_.size() ; ++i)
{
space->copyToReals(reals, states_[i]);
std::copy(reals.begin(), reals.end(), std::ostream_iterator<double>(out, " "));
out << std::endl;
}
out << std::endl;
}
但我需要那些原始形式的输出值,为双倍 . 出于这个原因,我想通过 ifstringstream
库使用我自己实现的以下函数来阅读它们:
std::ofstream solution_matrix;
pg->printAsMatrix( solution_matrix ); // generate the solution with OMPL and copy them into "solution_matrix"
std::istringstream istr; // generate a variable
std::string buffer; // the buffer in which the string is going to be copied t
double var1, var2; // dummies variables
while( getline( solution_matrix, buffer ) ) {
istr.str( buffer );
istr >> var1 >> var2 >> var3 >> var4 >> var5 >> var6 >> var7;
std::cout >> var1 >> var2; // did you copy all data!?!? Show me please!
}
我得到了很多编译错误,因为 getline
函数只接受std :: ifstream数据 .
继承我作为临时解决方案所做的事情:
- 创建了一个新的
ifstream
变量:
std :: ifstream input_matrix;
- 试图将输出的矩阵复制到输入中:
solution_matrix << input_matrix;
- 使用新变量调用getline函数:
getline(input_matrix,buffer);
我现在没有编译错误,但代码根本不起作用 . 另外,我不确定我是否以正确的方式做到了 .
环顾四周,我发现很多例子使用文件首先复制数据,然后用 ifstream
从同一个文件中读取 . 就像是:
// Print the solution path to a file
std::ofstream ofs("path.dat");
pg->printAsMatrix(ofs);
但要做到这一点,我需要创建一个新文件,将其保存在硬盘上,然后使用 ifstream
再次打开它:
std::ifstream file;
file.open( "path.dat" );
这种方式有效但我真的不想创建文件 . 有办法做到这一点:
-
没有创建文件;
-
逐行读取矩阵(我将对值进行排序);
非常感谢
1 回答
您可以将
std::stringstream
与std::getline
一起使用,它可以作为ostream
参数传递给您的函数 . 例如:此外,您的
<<
在您的cout语句中是错误的方式:应该:
EDIT
为了澄清这一点,这是一个完整的例子来说明这个工作:
这里
func
类似于你的printAsMatrix()
函数,因为它写入了一个ostream . 向量example
包含值0-9 . 输出是: