my stupid question.

I notice when reading examples of code that some people use cout and some use prinf. But what is the real difference, and is there any advantage of using one over the other?
printf is a C function.

cout is a C++ instance of a stream object.

I tend to use cout. I try not to make use of old C functionality.
Last edited on
that was simple enough... thanks.
> is there any advantage of using one over the other?

To print out hello world with a new line after it, any of these would do:

1
2
3
std::puts( "hello world" ) ;
std::printf( "hello world\n" ) ;
std::cout << "hello world\n" ;


std::puts() can only print out c-style strings,
std::printf() and std::ostream (std::cout) can handle built-in types too:

1
2
3
int i = 12345 ;
std::printf( "the number is %d\n", i ) ;
std::cout << "the number is" << i << '\n' ;


std::printf() is not type safe; this will result in undefined behaviour:

1
2
int i = 12345 ;
std::printf( "the number is %f\n", i ) ;


std::printf() is limited to built-in types;
std::ostream (std::cout) can be extended to handle user-defined types:

1
2
std::complex<double> c( 1.5, 2.3 ) ;
std::cout << "the complex number is " << c << '\n' ;


There are other differences; but this should do for a start.
std::cout is a global variable of type "output stream", declared in <iostream>, it is a part of the C++ I/O library.

std::printf is a function declared in <cstdio> it is a part of the C I/O library (which is included in C++)

C++ streams are versatile, customizable, and extensible. They are also rather complicated, few people care to learn them well.

C streams are very limited in what they can do and in what can be changed about them, and they are notoriously type-unsafe. Surprisingly few people care to learn them well either, but their basics are common knowledge because C has been around longer.

In a code example you may read on the web, if something can be done using either library, it doesn't really matter.

PS: wow, i took too long to type that
Last edited on
thanks again everyone.

I tend to use cout more, though I don't care to learn it well.
Topic archived. No new replies allowed.