Results 1 to 2 of 2

Thread: check for value?

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Aug 2000
    Posts
    1,091
    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

    Visual Studio 2010

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    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:
    Code:
    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:
    Code:
    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:
    Code:
    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.
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width