c++ - printf() 是否像 cout 一样将其参数转换为字符串?

标签 c++ c

我是从C开始学C++的,最近刚看了一本C++的教程书。在流简介部分,本书指出:

The << operator is overloaded so that the operand on the right can be a string or any primitive value. If this operand is not a string, the << operator converts it to string form before sending it to the output stream.

所以我想知道 C 中的 printf() 函数是否具有相同的效果。如果不是,请告诉我它们之间的区别。

最佳答案

当然,它必须以某种方式生成每个参数的字符串表示形式,这是打印内容所必需的。毕竟,打印涉及将字符流发送到输出设备,除非有字符序列,否则无法打印。

printf() 函数使用格式化字符串来控制如何解释每个参数以创建字符表示,以及如何在输出时格式化该表示。

请注意,当然不会发生外部可见的参数“转换”。没办法

printf("%d\n", 47);

可以把那个47原地变成一个字符串; C 使用按值调用,因此该函数仅获取该值的拷贝,然后它使用 %d 转换说明符中隐含的类型信息来确定如何生成两个字符 ' 4''7' 组成打印表示。

关于c++ - printf() 是否像 cout 一样将其参数转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36795715/

相关文章:

c - 如何区分到达 EOF 和到达错误的 fgets

c++ - Vim 找不到 C++ libavformat/libavutil 库(没有那个文件或目录)

c - 在 C 中命名类型时使用什么样式

c++ - 通过转换运算符调用显式实例化的模板函数

C++ char 数组空终止符位置

具有自定义数据的 C 二叉搜索树

java - Collat​​z 和其他序列 : how to get more precision easily and avoid segfault?

c++ - 整数溢出错误

C++ concat const char 与来自#define 的值

c++ - 如何正确使用#include 指令?