输出文件流的“<<”和 'put()' 之间的区别

Difference between '<<' and 'put()' for output filestreams

我想了解“<<”运算符和 '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' 相同的结果。

这是为什么?

当你使用out << 1时,你调用:operator<<(int val)而不是:operator<<(char val),那么他可以将int转换为std::string

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'.