-
clearing char arrays
Hi I have a char array- char buffer[33] and I was wondering if there is an easy function to clear it so that it is empty. I've been searching the net for a while and I can't seem to find one. There is stuff for c++ strings but I need to be able to clear a char array. Thanks :D
-
-
hmm ok am i doing it right
Code:
char buffer[33];
memset(buffer, ' ', 33);
it doesn't seem to be working this is the code i am having problems with
Code:
int magicmenuchanger(string line1, string line2, string line3)
{
int h=0;
int max=numspells+1;
int spellnum=1;
line1.append(addstring(line1, spell[h].name, spellnum));
cout<<line1<<endl;
h=h+3;
spellnum=spellnum+3;
line1.append(addstring(line1, spell[h].name, spellnum));
cout<<line1<<endl;
return 0;
}
string addstring(string x, string z, int number)
{
char buffer[33];
memset(buffer, ' ', 33);
itoa (number,buffer,16);
x.append(buffer);
x.append(". ");
x.append(z);
return x;
}
spell[0].name is bolt while spell[3].name is cure but when i tell it to cout line one it displays (edit) 1.bolt the first time which is corerct but then the second time it displays (/edit) 1. bolt1. bolt4. cure instead of just 1. bolt4. cure. I am not sure why.
-
When using memset, you should probably set the last character (buffer[32]) to '\0'). The way you have it after memset the char array is not null-terminated. I'm not sure it matters in this case, though.
Since you are using the C++ string class, you can also accomplish this task using stringstreams and manipulators in <sstream> and <iomanip>.
As far as the output being wrong the second time, just step through the code. After the first time through, line1 is "1. bolt". Then, you pass line1 as x to addstring. The addstring function starts with x (which is "1. bolt") and appends the number, then the ". ", then the second string. That means it returns "1. bolt" + "4" + ". " + "cure" or "1. bolt4. cure". But then, back in the magicnumberchanger function, you append the result of the function to line1 again, so you get "1. bolt" + "1. bolt4. cure", which is why the result is "1. bolt1. bolt4. cure".
Maybe just set line1 = to the return value of addstring, or get rid of the x parameter and always start with an empty string.
-
thank you all for your suggestions I figured it out thanks there was a simple error in my code's structure :D
-
Provided you are using your char arrays as C strings, then all you need is this:
buffer[0] = '\0';
-
writing your own function to clear the array would be rather simple as well....
Code:
void clearCharBuff(char *buf)
{
for(int x=0;x<33;x++)
{
buf[x]='\0';
}
}
i know you figured out the problem.... but it is good to be aware that there are many ways to solve a single problem.
-
Personally I would use '\0' instead of ' ' if you are using memset. You avoid a lot more problems that way.