繁体   English   中英

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

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

因此,我正在尝试创建一个程序,该程序从文件中读取字符,将其全部存储到字符数组中,然后写入新文件,只是每个字符的原始数量增加一个(这里最有经验的程序员会知道我在说什么)。 所以我基本上是在尝试制作自己的加密算法。 但是我收到一个非常奇怪的错误: <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] = '\0';

        cout << "Storing done, encoding..." << endl << endl;
        for(int i = 0; Str[i] != '\0'; 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而不是ofstream foutput (必须将其声明为输出流而不是输入流。

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

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


然后,您将在这里得到另一个错误:

 foutput << Str[i] += 1; 

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM