Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does calling cout.operator<<(const char*) print the address instead of the character string?

Tags:

c++

c++11

c++14

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.

like image 534
Pranjal Kaler Avatar asked Jul 31 '19 18:07

Pranjal Kaler


People also ask

What happens when you use std :: cout on the address or value of a char PTR?

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.

How do I print a char?

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.


1 Answers

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; 
like image 112
NathanOliver Avatar answered Oct 04 '22 18:10

NathanOliver