简体   繁体   中英

output char* to std::string C++

So given:

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

char* memory holds a curl return, XML doc.

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

So sizeof() I think is return the total bytes in the char*

How do I get what the actual value is a char* . So basically the whole curl return. Which is 5 lines of XML?

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.

If your curl return or whatever else is terminated by \\0 , then you can directly do the following

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. If your chunk.size contains the correct size, then you can use

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

std::string constructor can accept char* and data length ( see the 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. You want to initialize a string with this data so you will need to do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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