PDA

Click to See Complete Forum and Search --> : check for value?


softwareguy74
Jan 5th, 2001, 10:52 PM
Hi,

How can I test a char value to see if it has been assigned a value? Does that make sense? For example, if I declare a char such as:

char* test;

How can I test if it is empty or has a value? In VB, I can simply do the following:

if test = "" then...

any help would be appreciated..

Dan

parksie
Jan 6th, 2001, 04:05 AM
What I normally do is initialise any pointers to NULL before they're used. So that way you can avoid comparing a non-allocated string:

char *pcStr = NULL;

Allocate(pcStr, "Hello World");

...

void Allocate(char *pcPtr, char *pcString) {
if(pcPtr) delete[] pcPtr; // Ensure that there's nothing

pcPtr = new char[strlen(pcString) + 1];
strcpy(pcPtr, pcString);
pcPtr[strlen(pcString)] = '\0'; // Ensure null-terminated
}


To compare, use strcmp from string.h:

char *one = "Hello";
char *two = "World";

if(strcmp(one, two) < 0) {
// one is "less" than two (alphabetically)
}

if(strcmp(one, two) == 0) {
// one is equal to two
}

if(strcmp(one, two) > 0) {
// one is greater than two
}


So in your case, the final comparison would be:

char *pcStr;

if(pcStr && strlen(pcStr) == 0) {
// No value
}

That && syntax is used for "short-circuiting" a comparison, as in - if the first is false, then the rest of the statements are NOT executed. This allows you to verify the pointer BEFORE trying to use it and crashing your program.