C++ 如何使用fstream在堆栈中存储文本文件 #包括 #包括 #包括 使用名称空间std; int main() { 堆叠网页; fstream web1; fstreamweb2; fstreamweb3; web1.open(“web1.txt”,fstream::out); web2.open(“web2.txt”,fstream::out); web3.open(“web3.txt”,fstream::out); web1.close(); 网页推送(web1); cout&):正在尝试 引用已删除的函数
因此,我假设我这样做的方式是错误的。是否有一种方法可以将fstream文件存储在堆栈中?我假设您希望将文本存储在堆栈上的文件中,而不是实际的fstream对象中?如果是这样,将文件内容存储为字符串会更容易C++ 如何使用fstream在堆栈中存储文本文件 #包括 #包括 #包括 使用名称空间std; int main() { 堆叠网页; fstream web1; fstreamweb2; fstreamweb3; web1.open(“web1.txt”,fstream::out); web2.open(“web2.txt”,fstream::out); web3.open(“web3.txt”,fstream::out); web1.close(); 网页推送(web1); cout&):正在尝试 引用已删除的函数,c++,file,stack,fstream,C++,File,Stack,Fstream,因此,我假设我这样做的方式是错误的。是否有一种方法可以将fstream文件存储在堆栈中?我假设您希望将文本存储在堆栈上的文件中,而不是实际的fstream对象中?如果是这样,将文件内容存储为字符串会更容易 #include <iostream> #include <stack> #include <fstream> using namespace std; int main() { stack <fstream> webpages;
#include <iostream>
#include <stack>
#include <fstream>
using namespace std;
int main()
{
stack <fstream> webpages;
fstream web1;
fstream web2;
fstream web3;
web1.open("web1.txt",fstream::out);
web2.open("web2.txt",fstream::out);
web3.open("web3.txt",fstream::out);
web1.close();
webpages.push(web1);
cout << webpages.size() << endl;
system("pause");
}
#包括
#包括
#包括
#包括
int main()
{
std::stack网页;
for(const auto&文件:{“web1.txt”、“web2.txt”、“web3.txt”}){
std::fstream页面(文件);
std::stringstream-ss;
ss当我运行程序并出错时
-错误是什么?std::basic_fstream
对象是不可复制的,因此您无法执行您试图执行的操作。使用C++11,您可以使用std::move
将std::fstream
对象移动到std::stack
。这取决于文件的大小和堆栈区域。您可以可能无法在堆栈上存储文本文件,因为堆栈内存区域很小。请尝试“内存映射”取而代之的是文件。你能将名称存储在堆栈中并根据需要打开并附加到文件中吗?@ThomasMatthews我认为询问者询问的是std::stack
不是堆栈作为自动存储。我不确定这一点。询问者打开文件是为了写入,而不是读取。
#include <iostream>
#include <stack>
#include <fstream>
#include <sstream>
int main()
{
std::stack <std::string> webpages;
for(const auto& file : {"web1.txt", "web2.txt", "web3.txt"}) {
std::fstream page(file);
std::stringstream ss;
ss << page.rdbuf();
webpages.emplace(ss.str());
}
std::cout << webpages.size() << "\n"; // will print "3"
std::cout << "-- pages read --\n";
for(;!webpages.empty(); webpages.pop()) {
std::cout << webpages.top() << "\n";
}
}
#include <stack>
#include <fstream>
int main()
{
std::stack<std::fstream> webpages;
for(const auto& file : {"web1.txt", "web2.txt", "web3.txt"}) {
webpages.emplace(file, std::fstream::out);
}
for(;!webpages.empty(); webpages.pop()) {
webpages.top() << "some text\n";
}
return 0;
}