# cout vs printf ???

## Recommended Posts

BUnzaga    267
Hello I am new to programming in C++, and I am doing various tutorials, and for some time I was really frustrated and confused that in some tutorials they would tell me to use iostream and cout and in other tutorials they would tell me to use stdio.h and use printf. I finally learned that the stdio.h was for use with C and iostream is used for C++. My question is which is more standard? Are they both used in almost every application, or is one used and another not, or how do you decide which one you want to use? Which is better for gaming? Which should I memorize? Should I just remember the syntax for both, and just include both in all of my programs? Thanks, BUnzaga

##### Share on other sites
DevFred    840
Quote:
 Original post by BUnzagaHello I am new to programming in C++ [...] My question is which is more standard?

If you're programming in C++ use cout.

##### Share on other sites
thallish    202
Using cout would also be my recommendation, but more important be consistent with the use. Do not use both. IMO that just leads to cluttered code. It is no problem if you have learned both, more power to you, but with power comes responsibility[wink]. Well that was probably over the top, but you get the point.

Good Luck

##### Share on other sites
CTar    1134
cout should definitely be used. It's type-safe, easy to use, extendable, generic, etc. It sometimes surprise people that generally cout is actually faster than printf. There is absolutely no reason to use printf in a C++ program.

You should of course know the syntax of both, but use cout whenever possible. Also the header is called cstdio in C++, not stdio.h as it's in C.

##### Share on other sites
ToohrVyk    1595
Use an std::ostream, not std::cout.

##### Share on other sites
boldyman    138
In C++ you should always use cout. Because it is fast!!
Use the standard library where ever possible.

www.nextdawn.nl
www.moneyaside.com

##### Share on other sites
Captain P    1092
@ToohrVyk: I'm curious, why? Actually, now that I'm looking it up, it turns out that std::cout is an instance of std::ostream. I guess you're pointing at how global std::cout really is?

##### Share on other sites
MaulingMonkey    1728
Quote:
 Original post by BUnzagaMy question is which is more standard?

Both are part of the C++ Standard Library (where printf is found under it's new header <cstdio>).

Quote:
 Are they both used in almost every application, or is one used and another not, or how do you decide which one you want to use? Which is better for gaming? Which should I memorize?

Performance is a non issue for comparison (the actual drawing of the console dwarfs the cost of using either method to send information to the console) -- for the most part, their functionality overlaps, but a few key points which apply to any programs using them:

1) Iostreams use operator chaining instead of va_args -- this means your program can't crash because you passed the wrong number of arguments, as can happen with printf.

2) Iostreams use operator overloading instead of va_args -- this means your program can't crash because you passed an int and it was expecting a string, as can happen with printf.

3) Iostreams don't have native support for format strings (which is the major root cause of 1 and 2). This is generally a good thing, but sometimes they're useful. The boost format library brings this functionality to iostreams for those who need it, with defined behavior (throws an exception) rather than undefined (spewing out bits of memory, or goodness knows what else) behavior (as is the case with printf). That said, this currently falls outside the standard (although many parts of boost are being incorperated into the upcomming next version of C++)

4) Iostreams, unlike their snprintf equivilants, can handle variable length buffers directly themselves, instead of you the programmer being forced to deal with hardcoded cruft or extranious loops.

So yeah, I'd go with iostreams. Even though I learned about them only after, in effect, mastering printf, I've since let my knowledge of printf's specifiers fade for the most part, having not used them myself for years (although I still recall major type specifiers).

Quote:
 Should I just remember the syntax for both, and just include both in all of my programs?

Well, understanding the syntax of printf will at least help you understand other people's code -- but I wouldn't write new code using it. Let me put it this way: there's a reason many reasons an alternative method was introduced to C++'s standard library (to the point where I refuse to use the methods inherited from C in that area on principle). I also treat any reference on C++ that uses printf with extreme suspicion -- it hints of oudated, ancient information which tends to be at best misleading, and at all-too-often, downright wrong. Either that or ultraconservative programmers. Then again, that's because ultraconservative programmers tend to be misleading :P.

##### Share on other sites
Crypter    748
printf() is C, not C++. C++ only supports it for backward compatibility with C.
imo, there are only two reasons to use printf():

-If you are working with legacy C code, or
-You are working with a system without the C++ runtime library

If you are using C++, I recommend using cout for the many reasons listed,
and only use printf() if you have to.

##### Share on other sites
Bregma    9199
Quote:
 Original post by MaulingMonkeyWell, understanding the syntax of printf will at least help you understand other people's code -- but I wouldn't write new code using it. Let me put it this way: there [are] many reasons an alternative method was introduced to C++'s standard library.... I also treat any reference on C++ that uses printf with extreme suspicion -- it hints of oudated, ancient information which tends to be at best misleading, and all-too-often, downright wrong.

Quoted for emphasis.

--smw

##### Share on other sites
swiftcoder    18426
Quote:
 Original post by ToohrVykUse an std::ostream, not std::cout.

cout is an ostream, so I fail to see the point of this comment?

##### Share on other sites
jpetrie    13099
I'm no mind reader, but I suspect the comment has to do with generality.

Since, as you note, std::cout is an instance of std::ostream, it is possible for you to perform your output on an instance of std::ostream (or rather, a reference to one), instead of on std::cout directly
int DoSomething(std::ostream &outputSink){  outputSink << "Doing something complex..." << std::endl;  ComputeMeaningOfTheUniverse();  outputSink << "Okay, done." << std::endl;  return (42);}

You leave the determination of whether or not to output to stdout, stderr, or a file (in short, the actual concrete destination of the output) to the user of the function, who can presumably make a better-informed decision about that output destination than the function itself, especially if the IO is just an informative side-effect of the function (as in this case; it's just log output, the real meat of the function is the computation of the meaning of the universe).

This also means you could even provide a std::ostream instance (or subclass) with a no-op backing buffer, to suppress output altogether (although there are more ideal solutions to this problem, as it doesn't prevent the function from doing any of the overhead work to generate and format the output, but this may not be a concern).

##### Share on other sites
Quote:
Original post by swiftcoder
Quote:
 Original post by ToohrVykUse an std::ostream, not std::cout.

cout is an ostream, so I fail to see the point of this comment?

I'm guessing ToohrVyk is pointing out that if you have (for example) a class which takes a std::ostream as a parameter to its constructor, and then write to that rather than std::cout, then your code is that bit more flexible - output can be routed to a file, say, for a 'quiet mode'.

##### Share on other sites
SunTzu    286
Correct me if I'm wrong, but you can redirect cout to point to something else to achieve exactly the same effect with less need to pass around parameters?

##### Share on other sites
JohnBolton    1372
Well, it's not a slam-dunk. Formatting output using iostream is complicated and unwieldy. printf is a much better choice when you have to do a lot of formatting. However you can have the best of both worlds using boost::format.

##### Share on other sites
jpetrie    13099
Quote:
 Correct me if I'm wrong, but you can redirect cout to point to something else to achieve exactly the same effect with less need to pass around parameters?

Depends how you mean. You can redirect from the shell, but that's completely out of the program's control. You can replace the streambuf in code, but that's less intuitive than replacing what you write to, I feel (less obvious), and its clunky if you're going to need multiple redirects. But yes, its an option.

##### Share on other sites
ToohrVyk    1595
Quote:
 Original post by jpetrieI'm no mind reader, but I suspect the comment has to do with generality.

You have explained my thoughts very well. I was indeed hinting at the possibility to use your ostream-based code with any ostream, and not just std::cout.

If not for generality, std::cout does not offer a lot over printf: type-safety is commonly handled by most compilers for printf as well (detecting type mismatches between format string and provided arguments), and I find the syntax for printf to be much more elegant than the one for streams (which is why I'm so happy about OCaml using printf instead of C++ formatting). The only downside to printf in C++ (aside from generality issues) is that it's not idiomatic.

##### Share on other sites
jflanglois    1020
The one thing that is too bad about standard C++ streams is that it is harder to separate content from presentation. Of course, I'm not recommending you use printf, but certainly take a look at boost::format for a type-safe equivalent.

##### Share on other sites
BUnzaga    267
Hello and thank you for the informative responses! I was mainly trying to figure out when or why I would use one over the other, or if I should include both.

In my experience as a brand BRAND new C/C++ student, I was browsing around on the net looking for tutorials on C/C++. I would read through one and it would tell me to do my basic 'Hello World' program and everything was great, until I read a different tutorial and it had some totally different way to do it.

So I didn't know which way was 'right' or if the tutorials I was using were valid, or what the heck was going on. Finally I came accross the Zeus CMD tutorils which explained that printf went with stdio.h, which was for C, and that cout went with iostream, which was for C++.

In the Zeus tutorial he had an excersize showing how each was used for formatting, etc etc, and we included both header files, so I just started thinking what was the most common or industry standard way to use these two headers, and in which situation I would choose one over the other, or if I should just stick with one and disregard the other.

My end goal is to land a job as a game programmer, and eventually get into 3d programming and AI. I would also like to produce my own series of all kids of games ranging from simple single player puzzle or tetris games to the full scale multi-player games using client/server networking, databases, and all that other stuff that I have no idea about.

SO. With that information, what should I do?

##### Share on other sites
sharpnova    108
You'll get a lot of different answers to this.

A programmer who is well versed in C and C++ will use C-style IO.

printf is much more compact.

try printing out some number in showpoint, precision 2, non-scientific-notation, width 5.

in cout you'll have to throw something into the stream for each modifier, in printf it's just a compact 3 or 4 characters preceeding the variable.

##### Share on other sites
Zahlman    1682
Quote:
 Original post by BUnzagaHello and thank you for the informative responses! I was mainly trying to figure out when or why I would use one over the other, or if I should include both.In my experience as a brand BRAND new C/C++ student, I was browsing around on the net looking for tutorials on C/C++. I would read through one and it would tell me to do my basic 'Hello World' program and everything was great, until I read a different tutorial and it had some totally different way to do it.

C, C++, and the (commercial and/or available to the public) Internet have all been around for a long time. A lot of information out there is out of date. Worse yet, many people don't bother to keep current, and MANY people think they know a lot more about C and C++ than they really do ;), and write tutorials that hold everyone else back :(

Quote:
 My end goal is to land a job as a game programmer, and eventually get into 3d programming and AI. I would also like to produce my own series of all kids of games ranging from simple single player puzzle or tetris games to the full scale multi-player games using client/server networking, databases, and all that other stuff that I have no idea about.SO. With that information, what should I do?

Well, first of all expect it to take a long time to reach the end of your road, just like it would to reach the end of any other road of the same sort.

And then, start learning. And then make sure you know the basics.

##### Share on other sites
Zahlman    1682
Quote:
 Original post by sharpnovaYou'll get a lot of different answers to this.A programmer who is well versed in C and C++ will use C-style IO.

No, s/he wouldn't, necessarily. I can tell you that because I know from forum experience that both MaulingMonkey and myself are "well versed" in both languages, and I can be pretty confident Bregma is too, based on, well, his job - and I think I can safely speak for the three of us when I say none of us would readily go back to stdio when there are better options available.

Quote:
 printf is much more compact.try printing out some number in showpoint, precision 2, non-scientific-notation, width 5.

I assume you mean a floating-point value. Is it a float or a double or a long double? C++ doesn't care. (boost::format doesn't either).

Quote:
 in cout you'll have to throw something into the stream for each modifier, in printf it's just a compact 3 or 4 characters preceeding the variable.

Well, not really "preceding the variable"; it's stuff that's mixed in to a format string, while all the variables occur after. And, you know, each of those characters has some meaning, and is something you have to "throw in" separately, and think about. Compactness doesn't always translate into simplicity.

But when you do have a valid reason for embedding formatting information into a base string and then filling out that "template" (i18n/l10n comes to mind), there is boost::format.

##### Share on other sites
CTar    1134
Quote:
 Original post by sharpnovaA programmer who is well versed in C and C++ will use C-style IO.

No! A well-versed programmer in C++ knows Boost and therefore the choice will always be between iostreams and boost::format. You don't even get the option to print user-defined types using printf.

Quote:
 printf is much more compact.

Like boost::format which is also:
- type-safe
- efficient
- intuitive

Quote:
 try printing out some number in showpoint, precision 2, non-scientific-notation, width 5.in cout you'll have to throw something into the stream for each modifier, in printf it's just a compact 3 or 4 characters preceeding the variable.

And if you happen to make one slight mistake your whole program could crash without warning. If that was a good reason to use printf then we should all go back to use one-letter identifiers. We now have tools like auto-completion in our IDE and typing a couple of extra characters have never hurt anyone.

A beginner (as in at least a couple of months) writing code can easily chunk out 500 lines of code/day, but in a professional environment where quality of code and debugging is high-priority it's (at least in my experience) uncommon to write more than 100 lines of code/day (usually less, depending on the project). Also all your IO should be pretty isolated from other code anyway so how many calls to IO constructs do you actually make?

There are well-known problems with iostreams (most notably the lack of format/content seperation), but there are thousands of well-known very serious problems with printf.

##### Share on other sites
MaulingMonkey    1728
Sorry to necroishpost, but...

Quote:
 Original post by sharpnovaA programmer who is well versed in C and C++ will use C-style IO.

I used to think this. Then I actually became well versed in C++, and stopped taking for granted printf's numerous, fundamental problems. Especially when I tried teaching some of my friends how to program.

The moment the point finally sunk in completely?

Our yearbook came back, where everyone had written stuff. One of them contained a corney rerendition of "Hello World". I think it was "Hey Mike" or something.

The printf format specifier was wrong.

I hung my head in shame and resolved never to inflict printf upon anyone ever again.

## Create an account or sign in to comment

You need to be a member in order to leave a comment

## Create an account

Sign up for a new account in our community. It's easy!

Register a new account