如何将`const char *`转换为`char *`? [英] How to convert a `const char *` to simply `char *`?

查看:212
本文介绍了如何将`const char *`转换为`char *`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用pdCurses库,我的目标只是真正使用字符串在我的C + +控制台游戏,但curses mvinstr()函数或任何插入函数需要一个非-const char * 作为参数。

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.


  • 我的解决方案首先是简单地输入 string.c_str(),但是返回一个 const char * ,这显然不能使用函数。

  • 接下来我把(char *)string.c_str(),但这只会导致一个未处理的异常。

  • c $ c> char * test = string.c_str()但不能与 const 兼容。

  • 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我只是试过const_cast抛出和破坏....
我不知道为什么PDcurses只接受非const char指针.... =(

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.... =(

*缓冲区没有工作,当我使用这个代码(time_s是蜇):

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);

我甚至在mvinstr()之前停止,并检查缓冲区的内容是00/0
完全符合我的意图。

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

但我得到一个访问冲突指向xutility....

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

推荐答案

mvinstr(x,y,str)和其他从当前或指定的字符位置,并以 str (或 wstr )中的字符串形式返回它们。

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)."

函数实际上会修改字符串,因此不能安全地转换 const ,特别是 c_str 指定您不应修改返回的字符串。

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.

您需要的代码如下:

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

请注意,我避免了 mvinstr mvinnstr 以避免缓冲区溢出的可能性。

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

这篇关于如何将`const char *`转换为`char *`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆