c++ - 文件写入函数操作数错误
问题描述
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string filePath = "temporaryfile.txt";
std::ofstream twrite(filePath.data());
if (twrite.is_open())
{
std::string input;
std::cin >> input;
twrite << input;
}
filePath = "datafile.txt";
std::ifstream dwrite;
dwrite.open("datafile.txt");
if (dwrite.is_open())
{
std::string dfile[sizeof(dwrite)];
std::string tfile;
int i = 0;
while (std::getline(dwrite, tfile))
{
dfile[i] = tfile;
i++;
}
for (int i = 0; i < sizeof(dwrite); i++)
{
dwrite << dfile[i] << std::endl;
}
}
}
我正在将交付文件“twrite”转到文件“dwrite”。编写文件代码时出错:没有与这些操作数匹配的“<<”运算符。我怎样才能使用相同的操作数?
解决方案
在这段代码中:
std::ifstream dwrite;
您正在声明一个ifstream
,这是一个输入文件流,因此您只能从中读取。试图这样写:
dwrite << dfile[i] << std::endl;
// ^^ not supported for ifstream
不被允许。
如果你想从这个文件流中读取和写入,那么你可以像这样声明它:
std::fstream dwrite;
dwrite >> /* ... */; // ok
dwrite << /* ... */; // ok
推荐阅读
- azure-devops - Devops 构建管道 yaml - 当前的 .NET SDK 不支持针对 .NET Standard 2.0
- python - 在numpy中索引多个范围
- angular - 角度类型'{域:字符串[]; }' 不可分配给类型 'string | 颜色'
- c# - 如何降级 Autorest 扩展 - 特别是 C# 扩展?
- java - Android - 构建失败 - 任务':app:mergeReleaseResources'的执行失败
- r - 读取文件而不在 R 中提及其特定文件名
- android - 最后一个元素在 LazyColumn 中不可见。喷气背包组成
- database - 如何恢复oracle db脚本,使用分区时标准版可以使用
- javascript - 替换字符串中的数组值并根据值创建新字符串
- python - 在Python中将非常小的数字转换为更大的正值