how to compare a string to null...
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
jaepi
Practically a Master Poster
647 posts since Jul 2006
Reputation Points: 32
Solved Threads: 4
uhmm, what about the;
char temp[100];
how would compare to null...
btw, thank you...:D
jaepi
Practically a Master Poster
647 posts since Jul 2006
Reputation Points: 32
Solved Threads: 4
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) { } .
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
Does it work in C++ like this?:
if( *temp_ptr == 0 ) {}
Aia
Nearly a Posting Maven
2,392 posts since Dec 2006
Reputation Points: 2,224
Solved Threads: 218
its not working, i just press enter but it does not alert me that i placed nothing... T_T
jaepi
Practically a Master Poster
647 posts since Jul 2006
Reputation Points: 32
Solved Threads: 4
>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.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
> i just press enter but it does not alert me that i placed nothing.
Maybe the newline is getting the best of you...
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
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.
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734