尝试使用 fstream 将字符写入文件:'operator<<'不匹配

Trying to write a character to a file using fstream: no match for 'operator<<'

本文关键字:lt operator 不匹配 文件 fstream 字符      更新时间:2023-10-16

所以,我正在尝试创建一个程序,从文件中读取一个字符,将其全部存储到字符数组中,然后写入一个新文件,除了每个字符的原始数字增加一个(这里大多数有经验的程序员都知道我在说什么(。所以我基本上是在尝试制作自己的加密算法。但是我得到一个非常奇怪的错误: <various paths here>main.cpp|27|error: no match for 'operator<<' (operand types are 'std::ifstream {aka std::basic_ifstream<char>}' and 'char')|我听说过这个错误很多,但我所看到的只是当人们使用类定义的函数时才会发生,这是我在我的程序中没有做的事情。这个错误还附带了一个注释,我认为人们可能会发现它对帮助我很有用: <various paths here>main.cpp|27|note: no known conversion for argument 1 from 'std::ifstream {aka std::basic_ifstream<char>}' to 'int'|源代码如下:

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    int array_size = 1024000;
    char Str[array_size];
    int position = 0;
    long double fsize = position;
    ifstream finput("in.txt");
    ifstream foutput("out.txt");
    if(finput.is_open()) {
        cout << "File Opened successfully. Storing file data into array." << endl;
        while(!finput.eof() && position < array_size) {
            finput.get(Str[position]);
            position++;
            fsize = position;
            cout << "Processed data: " << fsize / 1000 << "KB" << endl;
        }
        Str[position-1] = '';
        cout << "Storing done, encoding..." << endl << endl;
        for(int i = 0; Str[i] != ''; i++) {
            cout << Str[i] << "changed to " << char(Str[i] + 1) << endl;
            foutput << Str[i] += 1;
        }
    } else {
        cout << "File could not be opened. File must be named in.txt and must not be in use by another program." << endl;
    }
    return 0;
}

注意:我一直在使用 fstream 在其他时候在文件中输出字符串(不是字符,请记住这一点(,它工作得很好!

ifstream foutput("out.txt");

这是输入流,而不是输出流。将其更改为 std::ofstream 以获取输出流。


然后,您将在此处收到另一个错误:

foutput << Str[i] += 1;

这是因为运算符优先级。通过插入括号来修复它:

foutput << (Str[i] += 1);

您已经声明了ifstream foutput而不是ofstream foutput(您必须将其声明为输出流而不是输入流。

  1. ifstream foutput("out.txt");替换为ofstream foutput("out.txt");
  2. 此外,将foutput << Str[i] += 1更改为foutput << (Str[i] += 1)以消除由于运算符优先级而导致的错误。