简体   繁体   English

char *到std :: string

[英]char* to std::string

I have a Character Array (char* pData) in C++, what i want to do is to copy some data (from pData) in std::string. 我在C ++中有一个字符数组(char * pData),我想要做的是在std :: string中复制一些数据(来自pData)。 The code looks like this: 代码如下所示:

std::string sSomeData(pData+8);//I want to copy all data starting from index 8 till end

The problem is that when above statement executes the string contains nothing in it. 问题是当上面的语句执行时,字符串中不包含任何内容。 I guess that my pData is not terminated with '\\0' thats why its not working. 我猜我的pData没有以'\\ 0'结尾,这就是为什么它不起作用。

Regards, Jame. 问候,詹姆斯。

如果您知道pData的大小,则可以使用construct-from-iterators构造函数:

std::string sSomeData(pData + 8, pData + size_of_pData);

If you don't know whether your data is NULL terminated or not then you should know the size of the data (ie how many characters are there). 如果您不知道您的数据是否为NULL终止,那么您应该知道数据的大小(即有多少个字符)。 Otherwise there is no way to copy it. 否则无法复制它。 When you know the size, you can specify it in the string constructor. 知道大小后,可以在字符串构造函数中指定它。 Following is a sample code: 以下是示例代码:

int main( void )
{
    char p[] = {'N','a','v','e','e','n'};
    std::string s(p+3, p+6);
    return 0;
}

使用std::string sSomeData(pData+8, pData+8+n)其中n是要复制的字符数。

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

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