Basicly I have volatile const char*
and want to create a string
.
The volatile
keyword here is in all likelyhood irrelevant(a misunderstanding from a previous dev), but cannot easily get rid of it (coming from other library).
cannot convert argument N from 'volatile const char *' to 'std::string
I could just use a const_cast
to cast the volatile
away (and making the compiler disregard volatile
/const
). Im interested in a solution not using const_cast
.
Do other methods exist, eg. could using a stringstream
perhaps be a solution ?
Just using a for loop, may be an option:
volatile const char* cstr = "hello world";
std::string str;
for (volatile const char* pC = cstr ; *pC != 0; ++pC) {
str.push_back(*pC);
}
You can use the STL algorithm std::transform()
to do an element-wise copy of your C string.
The transform function will effectively convert each volatile const char
to a char
-- a conversion that works without const_cast
. Using std::back_inserter()
, you can append the resulting characters to the end of your std::string
.
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
volatile const char* cstr = "hello";
std::size_t len = 6; // your string's length
// this implicitly converts 'volatile const char' argument to 'char' parameter
auto func = [] (char c) { return c; };
std::string str;
std::transform(cstr, cstr + len, std::back_inserter(str), func);
std::cout << "string=" << str << ".\n"; // outputs: string=hello.
}
Note that you cannot use std::strlen()
for the same reason -- if you don't have the size, you need to write your own loop to calculate it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With