c++ - 输出文件流的 '<<'和 'put()'之间的区别

标签 c++ fstream iostream

我试图理解'<<'运算符和'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/

相关文章:

c++ - 为什么使用hough变换进行直线检测时theta的范围是0~179?

c++ - 在我的网站上运行python,C,C++应用程序

c++ - 使用 C++ 文件流 (fstream),如何确定文件的大小?

c++ - 为什么 std::cout 将 volatile 指针转换为 bool?

c++ - OpenCV仅用一个样本计算协方差矩阵

c++ - 在这种情况下如何保持良好的数据封装?

C++:ios::app 在 fstream 中不需要 ios::out

c++ - 如何从 fstream 中获取数据,然后再获取?

c++ - std::copy raw data to cout in hex format using ostream_iterator<uint8_t> 打印出未格式化的数据。为什么?

c++ - 错字为 "cout < myint"。为什么它有效?