首页 > 解决方案 > 文件写入函数操作数错误

问题描述

#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”。编写文件代码时出错:没有与这些操作数匹配的“<<”运算符。我怎样才能使用相同的操作数?

标签: c++

解决方案


在这段代码中:

std::ifstream dwrite;

您正在声明一个ifstream,这是一个输入文件流,因此您只能从中读取。试图这样写:

dwrite << dfile[i] << std::endl;
    // ^^  not supported for ifstream

不被允许。

如果你想从这个文件流中读取和写入,那么你可以像这样声明它:

std::fstream dwrite;
dwrite >> /* ... */;  // ok
dwrite << /* ... */;  // ok

推荐阅读