尝试使用 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] = ' ';
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
(您必须将其声明为输出流而不是输入流。
- 将
ifstream foutput("out.txt");
替换为ofstream foutput("out.txt");
- 此外,将
foutput << Str[i] += 1
更改为foutput << (Str[i] += 1)
以消除由于运算符优先级而导致的错误。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 为什么 std::optional::operator=(U&&) 要求你是非标量类型?
- 'operator='已弃用:改用 QDir::setPath()
- <<操作员在下面的行中工作
- 过载'operator new'如何导致无限循环?
- 与'operator='不匹配(操作数类型'String'且"void")
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 处理"no operator found"
- 如何编写 operator= 用于使用虚拟方法与非平凡成员的匿名联合
- 运算符重载:"operator+"必须采用零个或一个参数
- 使用 operator() 扩展 Eigen::EigenBase
- 重载operator< & lt;作为会员打印
- Operator< & lt;重载隐藏其他
- 重载ostream&时转换错误无效;operator< & lt;
- std::ostream&operator< & lt; (std:: ostream&压力,压力& &;val)
- operator< & lt;在c++中为类中的类重载
- 将std::endl传递给std::operator<<
- operator< & lt;重载、名称空间和模板