简体   繁体   English

将char *输出到std :: string C ++

[英]output char* to std::string C++

So given: 因此给出:

struct MemoryStruct {
    char *memory;
    size_t size;
};

char* memory holds a curl return, XML doc. char* memory保存一个curl返回XML文档。

I am doing: 我在做:

if(chunk.memory) {
    std::cout << "char size is " << sizeof(chunk.memory) << std::endl;
    std::string s = "";
    for (int c = 0; c<sizeof(chunk.memory); c++) {
        s.push_back(chunk.memory[c]);
    }
    std::cout << "s: " << s.c_str() << std::endl;
}

I am only getting back <?xm 我只回来<?xm

So sizeof() I think is return the total bytes in the char* 所以sizeof()我认为是返回char *中的总字节数

How do I get what the actual value is a char* . 我如何获得实际值是char* So basically the whole curl return. 因此,基本上整个卷发返回。 Which is 5 lines of XML? XML的5行是哪一行?

sizeof(chunk.memory) will give always you size of a pointer which in your case seems to be 4. That's why you see only 4 characters in your std::string. sizeof(chunk.memory)将始终为您提供一个指针大小,在您的情况下,该大小似乎为4。这就是为什么在std :: string中仅看到4个字符的原因。

If your curl return or whatever else is terminated by \\0 , then you can directly do the following 如果您的curl返回值或其他以\\0结尾的\\0 ,则可以直接执行以下操作

std::string s(chunk.memory);

If your char * is not terminated by \\0 , then you need to know the length of the string - you cannot use sizeof(chunk.memory) for this. 如果您的char *不是以\\0结尾,那么您需要知道字符串的长度-您不能为此使用sizeof(chunk.memory) If your chunk.size contains the correct size, then you can use 如果您的chunk.size包含正确的大小,则可以使用

std::string s(chunk.memory, chunk.size);

std::string constructor can accept char* and data length ( see the docs ); std :: string构造函数可以接受char *和数据长度( 请参阅docs ); Example: 例:

  std::string s(chunk.memory, chunk.size);

So container will pre-allocate need space for your string and initialize with it. 因此,容器将为您的字符串预分配需要的空间并使用它进行初始化。

In MemoryStruct memory is the pointer to the first returned character and size is the number of characters returned. MemoryStruct memory是指向第一个返回的字符的指针, size是返回的字符数。 You want to initialize a string with this data so you will need to do: 您想要使用此数据初始化字符串,因此您需要执行以下操作:

s.assign(chunk.memory, chunk.size);

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

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