将字符数组附加到字符串 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13558472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
appending character array to string c++
提问by user1852056
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. Sorry to waste yall's time.
刚刚意识到我没有正确初始化 null 并且我原来的方法有效。很抱歉浪费你们的时间。
回答by Luchian Grigore
Try with
试试
buffer += myArray;
should do it. append
should also work if you null-terminate the array.
应该这样做。append
如果您以空值终止数组,也应该有效。
回答by hinafu
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'