C++: How to convert 'const char*' to char

2019-06-10 22:50发布

问题:

I know there are a lot of questions like this out there on StackOverflow, but I haven't been able to find any that help resolve my case. Whenever I try to do something like this:

// str = some string or char array

// some magic to get around fpermissive errors
stringstream convert;
convert << str;
// capture the stream's temporary string
const string store = convert.str();
// get a manageable array
const char* temp = store.c_str();

and then try to do something like atoi(temp[0]), I keep getting the classic conversion error that char couldn't be converted to const char. In the documentation for atoi and many other functions, const char is a required parameter. How can a char be sent in if there's only a const one? Does retrieving a char at a specific position auto-cast to char?

回答1:

I'm not sure if this is what is causing the error, but atoi takes as its parameter not a char, but the pointer to one. So instead of atoi(temp[0])

try this

atoi(&temp[0])

as that is a pointer.