Re: const char* to char* conversion
u.int.32.t@gmail.com wrote:
Perro Flaco wrote:
Because there are other functions that need "char*" as input, so I
get errors when I do: str1.c_str()
I would like to convert a string to a char*, or a const char* to
char*. Any advice?
Thanks!
The correct solution is to use function overloading:
#include <iostream>
void f(char *)
{
std::cout << "char *" << std::endl;
}
void f(char const * p)
{
std::cout << "char const *" << std::endl;
f(const_cast<char *>(p));
}
int main()
{
char const * x = "Hello";
f(x);
char * p = "Hello";
While this is kinda OK for an example like yours, if I saw it in my
student's work, I'd definitely lowered the grade. Initialising
a pointer to non-const char with a literal is allowed in C++ when it
really ought to be disallowed (and all who did that in their code
had to fix their code). A [much] better way would be
char p[] = "Hello";
f(p);
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask