Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a `const char *` to simply `char *`?

Tags:

c++

constants

I'm using the pdCurses library and am aiming to only really use strings in my C++ console game but the curses mvinstr() function or any insert function requires a non-const char * as a parameter.

  • My solution at first to this problem was simply entering in string.c_str(), but that returns a const char * which apparently doesn't work with the function.
  • Next I put (char *)string.c_str() but this only causes an unhandled exception.
  • Finally I just tried char *test = string.c_str() but that's not compatible with const either.

What do I do to solve this?

K i just tried const_cast() and i still get an exception thrown and break.... I don't know why PDcurses only takes non-const char pointers.... =(

alright making a char* buffer didn't work when i used this code (time_s is the sting):

size_t length; 
    char buffer[12]; 
    length=time_s.copy(buffer,5,0); 
    buffer[length]='\0';
mvinstr(time_loc_y, time_loc_x, buffer);

i even put a stop before mvinstr() and checked the buffer's contents which was "00 /0" EXACTLY WHAT I WANTED.

but i get an access violation point to "xutility"....

like image 869
Griffin Avatar asked Dec 13 '22 13:12

Griffin


2 Answers

mvinstr(x,y,str) and others "take characters (or wide characters) from the current or specified position in the window, and return them as a string in str (or wstr)."

The function will actually modify the string, so you cannot safely cast the const away, especially since c_str specifies that you should not modify the returned string.

You need something along the lines of:

const MAX = 100;
char buf[MAX];
mvinnstr(x, y, buf, MAX);
...error checking...
string s = buf;

Note that I avoided mvinstr in favour of mvinnstr to avoid the potential for buffer overflows.

like image 143
ikegami Avatar answered Jan 08 '23 05:01

ikegami


How about

char* buffer = &str[0];
int fetched_len = mvinnstr(time_loc_y, time_loc_x, buffer, str.size());
str.resize(fetched_len);

In general, though, you should make a writable buffer instead of removing const from a pointer that has it. e.g.

vector<char> charvec(MAX_LENGTH);
str = string(&charvec[0], mvinnstr(time_loc_y, time_loc_x, &charvec[0], charvec.size());
like image 41
Ben Voigt Avatar answered Jan 08 '23 04:01

Ben Voigt