输出文件流的"<<"和"put()"之间的区别



我正在努力理解'<lt;'运算符和用于将字符写入输出文件的"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,并输出一个值为1char

// ... 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'的值。

当您使用out << 1时,您调用:operator<<(int val)而不是:operator<<(char val),然后他可以将int强制转换为std::string

相关内容

最新更新