简体   繁体   English

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

[英]Difference between '<<' and 'put()' for output filestreams

I am trying to understand the difference between the '<<' operator and the 'put()' function for writing characters to an output file.我试图了解用于将字符写入输出文件的 '<<' 运算符和 'put()' 函数之间的区别。

My code:我的代码:

#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;
}

I get that out.put(x) converts the integer 1 into a character according ASCII code, but I don't understand why this doesn't happen when I use out << x .我知道out.put(x)根据 ASCII 代码将整数 1 转换为字符,但我不明白为什么当我使用out << x时不会发生这种情况。

However, out.put('a') does produce the same as out << 'a' .但是, out.put('a')确实产生与out << 'a'相同out << 'a'

Why is this?为什么是这样?

当您使用out << 1 ,您调用: operator<<(int val)而不是: operator<<(char val) ,然后他可以将intstd::string

int x = 1;

// This produces the incorrect result ...
out.put(x);

No, it converts the int to a char and outputs one char , with the value 1 .不,它将int转换为char并输出一个char ,值为1

// ... while this produces the correct result
out << x;

That does formatted output and outputs the the representation of the value x holds.这会格式化输出并输出值x持有的表示。 Most probably it'll show the character 1 which is different from the character with value 1 .最有可能它会表现人物1这是从值的字符不同1

// These two produce the same (correct) result
out.put('a');
out << 'a';

Yes, there's no conversion there.是的,那里没有转换。 Had you done你做了吗

int x = 'A';
out.put(x);
out << x;

You'd probably see A65 where A comes from the put(x) and 65 from the formatted output since 65 is often the value of 'A' .您可能会看到A65 ,其中A来自put(x)65来自格式化输出,因为65通常是'A'的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM