开发者

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. 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.

Regards, Jame.


If you know the size of the pData, you can use the construct-from-iterators constructor:

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 (i.e. how many characters are there). 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;
}


Use std::string sSomeData(pData+8, pData+8+n) where n is the number of characters that you want to copy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜