cout and printing strings

hi guys,

so a simple question that has me thinking

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include <iostream>

using namespace std;

int main()
{
    const char* bird = "Seagul";
    string name = "adam";

    cout << name[1] << endl; // prints d
    cout << bird << endl; // prints Seagul
    cout << name << endl; // prints adam
    cout << bird[3] << endl; // prints g
    cout << &bird[3] << endl; // prints gul
    
}


so when we print out bird[3] or fourth character of the string bird, why does it only print that char and not the string starting at bird[3]

but when we pass an address to cout such as &bird[3] it prints the string starting from the address specified until it finds the null character?

thanks
It's printing a single character because bird[3] is a single character not a string.

but how does cout distinguish between a char and a string?

Is the << operator overloaded?

one for a char and one for a char* with obviously the char version just printing a single char and the char* printing the string?

Last edited on
Is the operator<< overloaded?

Yes.

By the way the operator>> is also overloaded.

And don't forget that the operators are also overloaded for std::string as well as all the standard numeric types. You can also overload these operators for your own types as well.

thanks jlb :)
Topic archived. No new replies allowed.