简体   繁体   English

将字符数组附加到字符串c ++

[英]appending character array to string c++

I have a character array of 256 characters or char myArray[256] only the first couple actually hold any information 我有一个256个字符的字符数组或char myArray[256]只有第一对实际拥有任何信息

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 我不一定确切地知道数组中的内容,但我想将那里的内容(减去空字符)复制到我的缓冲区字符串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. 刚刚意识到我没有正确初始化null并且我的原始方式有效。 Sorry to waste yall's time. 很抱歉浪费你的时间。

Try with 试试吧

buffer += myArray;

should do it. 应该这样做。 append should also work if you null-terminate the array. 如果null终止数组, append也应该有效。

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' 此外,你应该这样做: myArray[5] = '\\0'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM