i cant figure out how, any ideas?
:)
Printable View
i cant figure out how, any ideas?
:)
Try const_cast< >( )
Here is a simple example.
Code:void g (const char& c)
{
val = f(const_cast<char&>(c));
}
worked, thanks :)
Dont use const_cast unless you really know what you are doing....
The reason why you are getting an error is that the string you are trying to copy the pointer of is const and so therefore should not be altered....and if you assigning it to a normal pointer, then that pointer has the ability to alter the string......
If the string is say a string literal, and you cast away the constness and if you then try to alter that string you may cause a fault that could crash your prog.....
Ony use const_cast if you are absolutely sure the pointer will not try change the data it points to
i want to change the data tho, its in a string type, and im doing
char *str = mystring.c_str();
Fine...but do it properly ;)
Code:#include <iostream>
#include <string>
int main(){
using std::cout;
using std::endl;
using std::string;
std::string mystring("Hello World");
mystring.replace(0,1,"M",1);
cout << "Changed " << mystring << endl;
}
im using it with something like this:
im gonna be working on that mroe today..but its pattern detection and stuff, but i converted them into ways i know how to work with themCode:char *pattern = const_cast<char*>(pat.c_str());
bool hitletter=true;
Trim(find);
if(strcmp(find,pattern)==0) {
return true;
}
Far easier...
Code:if(mystring.compare(find)==0) {
return true;
}
ahh ok, im new to string. i guess ill go find some docs
thanks :)
Typically when you need to manipulate a constant string/char array you would make a copy of that string/char array. Obviously not for this though.
Your problem here is the char* datatype. string.c_str returns a const char* and strcmp takes a const char* so there is absolutly no need to have anything but a const char*.
You almost never need to cast a const to non-const. If you find you need to do this, think about your program design and why it is const in the first place. Never cast a const to non-const.Code:const char* pattern = pat.c_str();
bool hitletter=true;
Trim(find);
if( strcmp( find, pattern ) == 0 ) return true;