hello there, im new in c++...i just want to know how to compare a string to null like:

string x;
cin >> x;

if(x==NULL){

cout << "null";

}

im using this one, if(&x==0) ...but it does'nt work...
this is what my mentor told me to do...

help..thanks

string class has no overloaded "==" operator. You can do

string temp;
      cin >> temp;
 
      if(temp.empty())
            cout << "null";

uhmm, what about the;

char temp[100];

how would compare to null...

btw, thank you...:D

Given char temp[100]; I guess you must be talking of how to determine is a string is empty. How about something like if(strlen(temp) == 0) { } .

its not working, i just press enter but it does not alert me that i placed nothing... T_T

>i just want to know how to compare a string to null
You don't. NULL is a null pointer and a string object isn't a pointer. Most likely you want to check for an empty string:

if ( x == "" )

or

if ( x.empty() )

And such.

>this is what my mentor told me to do...
Your mentor probably thought you were using C-style strings simulated with pointers. Your sample code isn't though, so that advice is useless.

>string class has no overloaded "==" operator.
Yes, it does. That's one of the selling points of the class.

>i just press enter but it does not alert me that i placed nothing...
Post your full program. We don't like playing 20 questions.

> i just press enter but it does not alert me that i placed nothing.

Maybe the newline is getting the best of you...

There is no 'null string' as such, only null pointers. A string instance can't be null because it has just been instantiated. And x != string::npos doesn't make sense either, one is a string object while the other is most probably an unsigned integer.

This article has been dead for over six months. Start a new discussion instead.