comparing C++ strings to null

Started by
8 comments, last by musasabi 16 years, 3 months ago
if(someString == '\0'); what _should_ i be using instead of that? EDIT: btw, ive tried someString.compare('\0'); and that causes it to crash and open up the strlen assembly. o.O (using VC++2005)
Advertisement
Depends. What are you trying to test? What type of string?

If the string is a char * and you want to check if the pointer is null, if (!str) { /* pointer is null */ }

If you want to check if the string is empty then if (!*str) { /* string is empty */ }

You could also compare against NULL or 0 directly.

EDIT: Guess you're using std::string in which case you'd use empty() as mentioned below.
Ra
Assuming someString is a std::string and you want to see if it's empty, I'd suggest
if (someString.empty( ))
Sometimes it's really that simple. [smile]
i just set the string to null before i ask the user for input and then use it as a condition to accept the input. like~ this:

filename = '\0';while(filename == '\0' || cin.fail()){	if(cin.fail())	{		cin.clear();		cin.ignore(numeric_limits<streamsize>::max(), '\n');	}	cout << ">>";	cin >> filename;}


that explodes nicely.
haha, god damnit this forum flies sometimes.

i tried using filename.empty and while it doesnt crash, it doesnt produce the desired result, either, haha.
There's no need to stick '\0' in the string. When you construct the std::string it will be empty. (A std::string containing '\0' is not the same as an empty string.)
Ra
Quote:Original post by musasabi
i just set the string to null before i ask the user for input and then use it as a condition to accept the input. like~ this:

*** Source Snippet Removed ***

that explodes nicely.


Don't bother giving the string any value other than "" to begin with. Leave it empty (std::string filename;), and check to see if it's empty. Unlike C strings, std::strings show emptiness by having no contents; their size is 0.

[Edit: Shoot, double Ra'd...]
yeah, but i need to reset it to a null-ish value in order to test it again (in this case, if the filename they enter doesnt exist, it loops back).
Quote:Original post by musasabi
yeah, but i need to reset it to a null-ish value in order to test it again (in this case, if the filename they enter doesnt exist, it loops back).

Simply empty it: filename.clear( ); or filename = "";.

Better yet, loop on the condition that the file isn't open, which is really what you're after:
bool fileOpen = false;while (!fileOpen){    //  get file name    //  try to open file    //  success?        fileOpen = true;}
ah, that works flawlessly. =)

thanks as always guys.

This topic is closed to new replies.

Advertisement