我试图理解'<<'运算符和'put()'函数之间的区别,该函数用于将字符写入输出文件。
我的代码:
#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'
相同的结果。为什么是这样?
最佳答案
int x = 1;
// This produces the incorrect result ...
out.put(x);
不,它将int
转换为char
并输出一个char
,其值为1
。// ... while this produces the correct result
out << x;
这样做会格式化输出并输出x
保留的值的表示形式。最有可能显示字符1
,该字符不同于具有1
值的字符。// These two produce the same (correct) result
out.put('a');
out << 'a';
是的,那里没有转换。你做完了吗int x = 'A';
out.put(x);
out << x;
您可能会看到A65
,其中A
来自put(x)
,而65
来自格式化输出,因为65
通常是'A'
的值。
关于c++ - 输出文件流的 '<<'和 'put()'之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64156861/