在我的项目中,我需要使用以下库(OMPL)。我特别感兴趣的是成员函数printAsMatrix(std::ofstream &out),它将数据输出到终端或文件。这里是函数
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;我现在没有编译错误,但代码根本无法工作。另外,我不太确定我是否做得对。
环顾四周,我发现了很多示例,首先使用文件复制数据,然后使用ifstream读取同一文件。类似于:
// Print the solution path to a file
std::ofstream ofs("path.dat");
pg->printAsMatrix(ofs);但要做到这一点,我需要创建一个新文件,将其保存在硬盘上,然后使用ifstream再次打开它。
std::ifstream file;
file.open( "path.dat" );这种方式工作,但我真的不想创建一个文件。有没有办法做到这一点:
许多人提前感谢
发布于 2014-12-08 21:58:54
您可以使用std::stringstream和std::getline,它可以作为ostream参数传递给您的函数。例如:
std::stringstream solution_matrix;
pg->printAsMatrix( solution_matrix );
std::string line;
while (std::getline(solution_matrix, line)) {
std::cout << line << std::endl;
}此外,您的<<在cout语句中是错误的:
std::cout >> var1 >> var2;应:
std::cout << var1 << var2;编辑
为了澄清这一点,这里有一个完整的例子来说明这一工作:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
void func(std::ostream&, const std::vector<double>&);
int main(int argc, char *argv[])
{
std::stringstream solution_matrix;
std::vector<double> example;
for (int i=0; i<10; ++i) {
example.push_back(i);
}
func(solution_matrix, example);
std::string line;
while (std::getline(solution_matrix, line)) {
std::cout << line << std::endl;
}
}
void func(std::ostream& out, const std::vector<double>& data)
{
std::copy(data.begin(), data.end(), std::ostream_iterator<double>(out, "\n"));
}这里,func类似于您的printAsMatrix()函数,因为它将写入一个ostream。向量example包含0-9的值.产出如下:
0
1
2
3
4
5
6
7
8
9https://stackoverflow.com/questions/27365810
复制相似问题