【问题标题】:Difference between '<<' and 'put()' for output filestreams输出文件流的 '<<' 和 'put()' 之间的区别
【发布时间】: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 &lt;&lt; x 时不会发生这种情况。

但是,out.put('a') 确实产生与 out &lt;&lt; 'a' 相同的结果。

这是为什么?

【问题讨论】:

  • ostream::put() 输出一个字符int 或任何其他类型没有重载。
  • &lt;&lt; 作为流操作符利用了转换、类型感知输出、区域设置和文化以及作为 C++ I/O 子系统一部分的转换器机制。有些人不喜欢这个工具,因为它为小程序带来了相当大的 I/O 子系统。 put 方法绕过了大部分机制,只输出给定的字符。

标签: c++ fstream iostream


【解决方案1】:
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' 的值。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 流插入器不会将int转换std::string。它将int转换为文本。强制转换是您在源代码中编写的内容,用于告诉编译器进行转换。
    猜你喜欢
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 2021-11-15
    • 2012-06-20
    • 2017-06-21
    • 2020-09-06
    相关资源
    最近更新 更多