-
August 21st, 2008, 11:10 AM
#1
How to see if char array is empty???
I have a char array, char cCallProgram[8];
After running some code I need to see if the array is == spaces..
I am trying to do
memcmp(cCallProgram, ' ', sizeof(cCallProgram))
Its complaining about the 2nd parameter.. How can I make this work?
-
August 21st, 2008, 11:20 AM
#2
Re: How to see if char array is empty???
Well, assuming you want to match *specific* character (the space, ASCII code 32), you could do
Code:
memcmp(cCallProgram, " ", 8);
with 8 spaces in the string.
If *any* form of whitespace were good enough, you'd need something like:
Code:
for(i = 0; i < 8; i++)
if (!iswhite(cCallProgram[i]))
return false;
return true;
Alternatively using C++ strings, there's always
Code:
string strCallProgram(cCallProgram,8);
if (strCallProgram.find_first_not_of(" \n\r\t") == string::npos)
return true;
return false;
Last edited by Lindley; August 21st, 2008 at 11:23 AM.
-
August 21st, 2008, 11:30 AM
#3
Re: How to see if char array is empty???
Your second argument is not a char* but a char.
Do you have to use C or can you use C++?
If you can use C++, then there is a really easy way to check char array sizes (if they are intended to be used as strings rather than raw data) which is less error prone than using memcmp.
Code:
size_t getStringLength(const std::string str) {return str.size();}
std::cout << getStringLength("Hello World") << std::endl; // prints 11 : Note does not include null terminator
Similarly, if you want to compare two char arrays then you can do the following
Code:
bool areEquivalent(const std::string str1, const std::string str2){return str1==str2;}
std::cout << areEquivalent("Hello World","Hello World") << std::endl; //true
std::cout << areEquivalent("Hello World","World") << std::endl; //false
If you can only use C then you probably want to do something like:
Code:
size_t len1=strlen(str1);
size_t len2=strlen(str2);
int result = memcmp ( str1, str2, len1>len2?len1:len2 );
-
August 21st, 2008, 12:13 PM
#4
Re: How to see if char array is empty???
I'd use strcmp instead of memcmp, but are you sure you really want to test for 8 spaces? As far as C or C++ that's not the same as empty, which would be indicated by a null in the first byte.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|