I was exploring the ostream
class in C++. I am stuck on the strange output of cout
on string and integer data types.
When passing an integer or floating-point value, the output is exactly what I pass. For example cout.operator<<(10);
prints 10
. But when passing a string as an argument it is printing some hexadecimal values:
#include <iostream> #include <string> using namespace std; int main() { const char* str = "aia"; cout.operator<<(str); return 0; }
Output: 0x4007e0
.
The reason for that is that std::cout will treat a char * as a pointer to (the first character of) a C-style string and print it as such.
You want to use %s , which is for strings (char*). %c is for single characters (char). An asterisk * after a type makes it a pointer to type.
When you do cout.operator<<(str)
you call cout
's operator <<
member function. If we look at what member functions overloads cout
has we have
basic_ostream& operator<<( short value ); basic_ostream& operator<<( unsigned short value ); basic_ostream& operator<<( int value ); basic_ostream& operator<<( unsigned int value ); basic_ostream& operator<<( long value ); basic_ostream& operator<<( unsigned long value ); basic_ostream& operator<<( long long value ); basic_ostream& operator<<( unsigned long long value ); basic_ostream& operator<<( float value ); basic_ostream& operator<<( double value ); basic_ostream& operator<<( long double value ); basic_ostream& operator<<( bool value ); basic_ostream& operator<<( const void* value ); basic_ostream& operator<<( std::nullptr_t ); basic_ostream& operator<<( std::basic_streambuf<CharT, Traits>* sb); basic_ostream& operator<<( std::ios_base& (*func)(std::ios_base&) ); basic_ostream& operator<<( std::basic_ios<CharT,Traits>& (*func)(std::basic_ios<CharT,Traits>&) ); basic_ostream& operator<<( std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );
If you notice, there isn't one for a const char*
, but there is one for a const void*
. So, your const char*
is converted to a const void*
and that version of the function prints the address held by the pointer.
What you need to do is call the non member function overload of operator<<
and to do that you can use
cout << str;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With