Editing
C++
(section)
Jump to navigation
Jump to search
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Prefer iostreams to printf and scanf=== Most developers are familiar with the C-style printf statement syntax, for example: printf ("The result is %d\n", i); The drawback of this approach is that the formatting code depends on the type of i. Even worse, it may vary depending on the OS and whether we are using 32 bit or 64 bit. For example. maybe that formatting code should be "%ld" or "%lld" or "%Ld". The first is for long ints, the second for long long ints, and the third is system dependent. Which would you use for a 64 bit length integer? The answer to that is system dependent. Since we compile our code on many systems, and both as 32 bti and 64 bit, it is important to avoid this conundrum. (In templated code this situation is even worse). The C++ iostream equivalent to the above is: std::cout << "The result is " << i << "\n"; Now the compiler will make the right conversion for us, regardless of what <tt>i</tt> is. More complicated printf style formatting can also be converted to iostrings, for example: printf ("The result is %.3f\n", x); becomes std::cout << "The result is " << setprecision(3) << x << "\n"; On the other hand, the standard C++ stream formatting modifiers like this example, although overloaded to correctly match the variable type, tend to be overly verbose to conveniently use. I recommend therefore using boost::format where specific formatting is required. It is overloaded and will correctly match the variable type and length, but can be used with the familiar and concise POSIX format strings. boost::format has already been adopted in the next official C++ standard. Here is an example using boost::format: std::cout << format("The result is %.3f\n") % x;
Summary:
Please note that all contributions to bone.wiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
BoneWiki:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Navigation menu
Personal tools
Not logged in
Talk
Contributions
Log in
associated-pages
Page
Discussion
English
Views
Read
Edit
View history
More
Search
Navigation
Main page
Documents
Recent changes
Help
Tools
What links here
Related changes
Page information