C++ 逐行读取std::ofstream(但不从文件中读取)
在我的项目中,我需要使用以下库()。我特别感兴趣的是成员函数printAsMatrix(std::ofstream&out),它将数据输出到终端或文件。以下是: 由于只接受std::ifstream数据的C++ 逐行读取std::ofstream(但不从文件中读取),c++,inputstream,ifstream,outputstream,ofstream,C++,Inputstream,Ifstream,Outputstream,Ofstream,在我的项目中,我需要使用以下库()。我特别感兴趣的是成员函数printAsMatrix(std::ofstream&out),它将数据输出到终端或文件。以下是: 由于只接受std::ifstream数据的getline函数,我得到了很多编译错误 因此,继承我作为临时解决办法所做的工作: 创建了一个新的ifstream变量: std::ifstream输入矩阵 试图将输出矩阵复制到输入中: 解决方案矩阵您可以将std::stringstream与std::getline一起使用,它可以作为ostr
getline
函数,我得到了很多编译错误
因此,继承我作为临时解决办法所做的工作:
ifstream
变量:
std::ifstream输入矩阵解决方案矩阵您可以将
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;
}
应该是:
std::cout << var1 << var2;
我想一个成熟的人会得到你想要的,但从你的描述中很难说。无论如何,值得一试。谢谢。请你举个例子好吗?不太好,因为我不知道你想做什么。不过,底线是放弃磁盘上的文件流,对
std::stringstream
执行printAsMatrix(ss)
,然后将get pos定位到您想要的位置,并开始通过常规流操作(理论上)在数据中滑动。你不会一行一行地得到你的目标(没有自定义的streambuf导数很难做到),但你会得到你的内存目标。非常感谢。但你确定吗?因为我从编译器中得到了以下错误:错误:“std::ofstream”没有名为“str”的成员。
该错误表明您输入了错误。它应该是str,而不是srt。我还将ofstream更改为ostream,这与您在回答中给出的函数减速相匹配。您确定吗?std::ostream只是一个框架,据我所知无法构造……无论如何……我认为你是不对的,因为我从编译器中得到了相同的错误(即使使用ostream-no f),因为它没有.str()成员函数。即使我也找不到这样的函数
// Print the solution path to a file
std::ofstream ofs("path.dat");
pg->printAsMatrix(ofs);
std::ifstream file;
file.open( "path.dat" );
std::stringstream solution_matrix;
pg->printAsMatrix( solution_matrix );
std::string line;
while (std::getline(solution_matrix, line)) {
std::cout << line << std::endl;
}
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"));
}
0
1
2
3
4
5
6
7
8
9