I guess i'm missing something basic, but i'm new to C++ and do not know how do these streams behave.

Can someone please explain why no text is printed to the screen in the following example:

#include <iostream>

using namespace std;
int main (void)
{
    char *ptr = NULL;
    cout << ptr << "This is a sample text." << endl;
    return 0;
}

Why do you have a ptr variable if you're doing nothing with it? Try changing your code to:

#include <iostream>

using namespace std;
int main (void)
{
    cout << "This is a sample text." << endl;
    return 0;
}

ok...thank you very much jonsca...that was excatly what i was trying to find
it's not that i used NULL pointer for nothing, it's my function that returns some strings and in some conditions it returns null pointer

okay...in order to make things a bit clearer i'll try to copy relevant posts to one place: this

#include <iostream>

using namespace std;
int main (void)
{
    char *ptr = NULL;
    cout << ptr << "This is a sample text." << endl;
    return 0;
}

This is sample text doesn't get printed since there are some errors that NULL pointer has caused to the stream. actually the current internal error state flag of the stream - badbit - is set, as a result of mentioned operation.

so, check these links:
http://www.cplusplus.com/reference/iostream/ios/rdstate/
http://www.cplusplus.com/reference/iostream/ios/clear/

#include <iostream>

using namespace std;
int main (void)
{
    char *ptr = NULL;
    cout << ptr << "This is a sample text." << endl;
    if ((cout.rdstate() & iostream::badbit) != 0)
    {
        cout.clear(iostream::goodbit);
        cout << "Error fixed!!!" << endl;
    }
    else
        cout << "There was no badbit!" << endl;

    return 0;
}

// Please note that badbit is internal error flag that can also
// be accessed through iostream::badbit, istream::badbit, ostream::badbit,
// fstream::badbit, ifstream::badbit, ofstream::badbit, etc. you just need
// appropriate headers

some say that badbit will always be set as a result of putting NULL pointer in the stream and that you can count on this.

but! some people say that sample code above will always act undefined. question is: what to do? well, you can try playing with badbit, and i think that it isn't a bad idea

there was a solution offered by "Rapscallion" - a poster, who said that overloading operator << should do the trick:

std::ostream& operator<< (std::ostream& os, const char* p)
{
    if (p)
        os.write (p, strlen (p) +1);
    else
        os.write ("NULL", sizeof("NULL"));
    
    return os;
}

it seems to me that this doesn't work. even if you replace strlen(p) with sizeof(p) it still doesn't act as it should

hope this helps, at least a bit, those who had faced this or similar problem

cheers :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.