Saturday, 15 March 2014

Are there any major advantages to using printf() over cout in C++? -



Are there any major advantages to using printf() over cout in C++? -

this question has reply here:

printf vs cout in c++ 15 answers

there situations where, in c++ scanf() preferable cin, wondering if there situations printf() more practical cout.

what can using ostream interface (so cout) far superior old style printf(). first of all, type safe, won't segmentation violation when mistakenly utilize wrong formatting sequence.

an example. imagine have print out attributes of struct stat returned posix fstat function. types of attributes defined using scheme dependant typedefs:

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; /* grouping id of owner */ dev_t st_rdev; /* device id (if special file) */ off_t st_size; /* total size, in bytes */ /* ... more attributes */

};

so things dev_t different types (typedefs) on different systems. may find on particular scheme dev_t equivalent to, say, int, , write this:

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

and work on system, when compile on system, defines, example, dev_t not int but, say, long, code compile, crash in runtime.

if utilize c++ streams , overloaded << operator stuff work correctly:

cout << "dev_t=" << s.st_dev;

another of import advantage of c++ streams extensibility. not possible extend set of formatting sequences printf understands. in contrast, can overload << operator conveniently print objects of own types.

c++ printf scanf cout cin

No comments:

Post a Comment