【发布时间】:2021-01-17 06:19:59
【问题描述】:
我正在尝试了解用于将字符写入输出文件的“
我的代码:
#include <fstream>
using namespace std;
int main() {
ofstream out ("output.txt");
int x = 1;
// This produces the incorrect result ...
out.put(x);
// ... while this produces the correct result
out << x;
// These two produce the same (correct) result
out.put('a');
out << 'a';
out.close;
}
我知道out.put(x) 根据 ASCII 码将整数 1 转换为字符,但我不明白为什么我使用 out << x 时不会发生这种情况。
但是,out.put('a') 确实产生与 out << 'a' 相同的结果。
这是为什么?
【问题讨论】:
-
ostream::put()输出一个字符。int或任何其他类型没有重载。 -
<<作为流操作符利用了转换、类型感知输出、区域设置和文化以及作为 C++ I/O 子系统一部分的转换器机制。有些人不喜欢这个工具,因为它为小程序带来了相当大的 I/O 子系统。put方法绕过了大部分机制,只输出给定的字符。