Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

appending character array to string c++

Tags:

c++

string

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.

like image 816
user1852056 Avatar asked Nov 26 '12 03:11

user1852056


People also ask

Can I append a char to a string?

Use the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling. string.

How do you concatenate a character array?

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.

Is string concatenation possible in C?

As you know, the best way to concatenate two strings in C programming is by using the strcat() function.


2 Answers

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'

like image 153
hinafu Avatar answered Sep 27 '22 16:09

hinafu


Try with

buffer += myArray;

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

like image 32
Luchian Grigore Avatar answered Sep 27 '22 16:09

Luchian Grigore