10

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.

5
  • 2
    Your "working code" is completely different. You're missing the =NULL part. Which is it? Commented Nov 26, 2012 at 4:02
  • @LuchianGrigore, will all values of mychararray after index 4 not be NULL by default (this is an actual question, I'm quite inexperienced at c++)? Commented Nov 26, 2012 at 4:04
  • 3
    @usernametbd no - if you want them to be 0, set them to 0 yourself explicitly, or just do: char mychararray[256] = { 0 }; Commented Nov 26, 2012 at 4:04
  • You're code (up top, with nulls) should work - see cplusplus.com/reference/string/string/append ... How does 'append' know the size of mychararray? Commented Nov 26, 2012 at 4:04
  • Your code should work once you add null termination (link). Commented Nov 26, 2012 at 4:05

2 Answers 2

10

Try with

buffer += myArray;

should do it. append should also work if you null-terminate the array.

Sign up to request clarification or add additional context in comments.

Comments

3

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'

2 Comments

=NULL and ='\0' are equivalent.
He didn't initialize the array, that's why he should put that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.