在C ++中使用printf()而不是cout有什么主要优点吗?

时间:2013-02-07 17:30:14

标签: c++ printf scanf cout cin

很明显,在C ++ scanf()cin更可取的情况下,我想知道是否存在printf()cout更实用的情况。< / p>

2 个答案:

答案 0 :(得分:4)

简答:永远! 在c ++中总是使用cout而不是printf是有意义的,因为它提供了类似于printf的类型安全性。

答案 1 :(得分:3)

使用ostream界面(cout)可以做的事情远远优于旧样式printf()。首先,它是类型安全,因此当您错误地使用错误的格式化序列时,您不会受到任何分段违规。

一个例子。想象一下,你必须打印出Posix struct stat函数返回的fstat的属性。使用系统相关的typedef定义属性的类型:

struct stat {
    dev_t     st_dev;     /* ID of device containing file */
    ino_t     st_ino;     /* inode number */
    mode_t    st_mode;    /* protection */
    nlink_t   st_nlink;   /* number of hard links */
    uid_t     st_uid;     /* user ID of owner */
    gid_t     st_gid;     /* group ID of owner */
    dev_t     st_rdev;    /* device ID (if special file) */
    off_t     st_size;    /* total size, in bytes */
   /* ... more attributes */

};

因此dev_t之类的东西在不同的系统上是不同的类型(typedef)。您可能会发现在您的特定系统上dev_t等同于int,并写下:

printf("dev_t=%d", s.st_dev);

它可以在您的系统上运行,但是当您在另一个系统上编译它时,例如,dev_t不是int,而是long,那么代码将编译,但在运行时崩溃。

如果你使用C ++流和重载<<运算符,那么东西将始终正常工作:

cout&lt;&lt; “dev_t =”&lt;&lt; s.st_dev;

C ++流的另一个重要优势是可扩展性。无法扩展printf理解的格式序列集。相反,您可以轻松地重载<<运算符,以方便地打印您自己类型的对象。

相关问题