I have a character array of 256 characters or char myArray[256]
only the first couple actually hold any information
myArray[0] = 'H';
myArray[1] = 'E';
myArray[2] = 'L';
myArray[3] = 'L';
myArray[4] = 'O';
myArray[5] = NULL;
myArray[6] = NULL;
// etc...
I won't necessarily know exactly what is in the array, but I want to copy what is there, minus the null characters, to my buffer string string buffer
I thought the appropriate way to do this would be by doing the following:
buffer.append(myArray);
And the program would stop reading values once it encountered a nul character, but I'm not seeing that behavior. I'm seeing it copy the entirety of the array into my buffer, null characters and all. What would be the correct way to do this?
Edit: Some working code to make it easier
#include <string>
#include <iostream>
using namespace std;
int main()
{
string buffer;
char mychararray[256] = {NULL};
mychararray[0] = 'H';
mychararray[1] = 'e';
mychararray[2] = 'l';
mychararray[3] = 'l';
mychararray[4] = 'o';
buffer.append(mychararray);
cout << buffer << endl;
return 0;
}
Just realized I wasn't initializing the null properly and my original way works. Sorry to waste yall's time.
Use the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling. string.
The strcat() method is used to concatenate strings in C++. The strcat() function takes char array as input and then concatenates the input values passed to the function. In the above example, we have declared two char arrays mainly str1 and str2 of size 100 characters.
As you know, the best way to concatenate two strings in C programming is by using the strcat() function.
This should do the work:
int c;
while(myArray[c] != NULL) {
buffer.append(1,myArray[c]);
++c;
}
Also, you should do something like this: myArray[5] = '\0'
Try with
buffer += myArray;
should do it. append
should also work if you null-terminate the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With