简体   繁体   English

如何将`const char *`转换为`char *`?

[英]How to convert a `const char *` to simply `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. 我正在使用pdCurses库,我的目标是只在我的C ++控制台游戏中使用字符串,但是curses mvinstr()函数或任何insert函数都需要非const char *作为参数。

  • 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. 我的解决方案首先解决这个问题只是输入string.c_str() ,但是返回一个const char * ,它显然不适用于该函数。
  • Next I put (char *)string.c_str() but this only causes an unhandled exception. 接下来我把(char *)string.c_str()但这只会导致一个未处理的异常。
  • Finally I just tried char *test = string.c_str() but that's not compatible with const either. 最后我只尝试了char *test = string.c_str()但这也与const不兼容。

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.... =( 我只是尝试了const_cast(),我仍然得到一个异常抛出和中断....我不知道为什么PDcurses只采用非const char指针.... =(

alright making a char* buffer didn't work when i used this code (time_s is the sting): 好吧,当我使用这段代码时,使用char *缓冲区不起作用(time_s是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. 我甚至在mvinstr()之前停了一下,并检查了缓冲区的内容是“00/0”我想要的是什么。

but i get an access violation point to "xutility".... 但我得到一个访问违规点“xutility”....

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 )." mvinstr(x,y,str)和其他“从窗口中的当前或指定位置获取字符(或宽字符),并将它们作为str (或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. 该函数实际上将修改字符串,因此您无法安全地转换const ,尤其是因为c_str指定您不应修改返回的字符串。

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. 请注意,我避免mvinstr支持mvinnstr以避免缓冲区溢出的可能性。

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. 但是,一般情况下,您应该创建一个可写缓冲区,而不是从包含它的指针中删除const eg 例如

vector<char> charvec(MAX_LENGTH);
str = string(&charvec[0], mvinnstr(time_loc_y, time_loc_x, &charvec[0], charvec.size());

Cautiously - if the code that uses the was- const data tries to modify it, anything can happen. 谨慎 - 如果使用was- const数据的代码试图修改它,任何事情都可能发生。

In short: 简而言之:

const std::string str = "...";
char *caution = const_cast<char *>(str.c_str());

However, given that you are getting unhandled exceptions, you probably need to make a modifiable copy of the constant string before calling mvinstr() . 但是,鉴于您正在处理未处理的异常,您可能需要在调用mvinstr()之前mvinstr()常量字符串的可修改副本。 Maybe: 也许:

const std::string str = "...";
char *caution = new char[str.length()+1];
str.copy(caution, str.length()+1);
...call to mvinstr()...
delete[] caution;

Since mvinstr is actually storing data into the array pointed at by the char* , you can't use a string there. 由于mvinstr实际上是将数据存储到char*指向的数组中,因此不能在那里使用string You need to allocate an array of char, pass that to mvinstr , and then transfer the characters to a string if you want. 您需要分配一个char数组,将其传递给mvinstr ,然后根据需要将字符传输到string

If you were using a function that could have been declared with a const char * (ie it doesn't actually modify the array), then you could use const_cast<> to remove the const . 如果您使用的函数可以使用const char *声明(即它实际上不会修改数组),那么您可以使用const_cast<>来删除const

const_cast<char *>(str.c_str());

But that's not what you're doing here. 但那不是你在这里做的。 const_cast might work if you tried it, but it would be by accident, not because it's supposed to work, and a new compiler or library version could break it at any time. 如果你尝试过const_cast可能会有效,但这可能是偶然的,不是因为它应该工作,而且新的编译器或库版本可能随时打破它。

Try something like the following, then use buffer wherever you need a char* . 尝试类似下面的内容,然后在需要char*地方使用buffer As Ben mentioned, you need to be very careful to keep the buffer larger than the string plus null terminator. 正如Ben所提到的,你需要非常小心地保持缓冲区大于字符串加上null终止符。

const int BUFFER_SIZE = 255;

string str ("Your string");
char buffer[BUFFER_SIZE];
if (str.length() < BUFFER_SIZE)
{
    size_t copy_length;
    copy_length=str.copy(buffer,str.length(),0);
    buffer[copy_length]='\0';
}

Removing const can be done with const_cast , and is sometimes necessary for using legacy interfaces that were written in C and don't use const. 删除const可以使用const_cast完成,有时需要使用用C编写的旧版接口并且不使用const。 In such cases, you can do: 在这种情况下,你可以这样做:

char* ptr = const_cast<char*> (str.c_str());

However, from the cplusplus reference page on c_str (): 但是,从c_str ()上的cplusplus参考页面:

The returned array points to an internal location with the required storage space for this sequence of characters plus its terminating null-character, but the values in this array should not be modified in the program and are only granted to remain unchanged until the next call to a non-constant member function of the string object. 返回的数组指向一个内部位置,该位置具有此字符序列所需的存储空间及其终止的空字符,但此数组中的值不应在程序中修改,只有在下次调用时才会保持不变。字符串对象的非常量成员函数。

This means that it is your responsibility to ensure that ptr is not used to modify the string, and you must handle the lifetime of ptr appropriately. 这意味着您有责任确保使用ptr来修改字符串,并且必须适当地处理ptr的生命周期。 Ie, you cannot continue to use ptr after str is out of scope, or after you call any non-const methods on str . 即,在str超出范围之后,或者在str上调用任何非const方法之后,您无法继续使用ptr If you do that, you go into Undefined Behavior, and will likely crash. 如果你这样做,你会进入未定义的行为,并可能会崩溃。

If you are looking for a safe way to interact with a legacy interface that takes char* , you can make your own writable copy: 如果您正在寻找一种安全的方式来与使用char*的旧接口进行交互,您可以创建自己的可写副本:

char* ptr = new char[ str.size() + 1 ];
strcpy(ptr, str.c_str());
ptr[str.size()] = '\0';
// ... use ptr as much as you want...
delete [] ptr;

if (string.empty()) foo(const_cast<char*>(string.c_str());

a better but still evil way to remove const is const_cast(const_string); 一个更好但仍然邪恶的方法来删除const是const_cast(const_string); (its better to find via grep/search) (通过grep / search查找更好)

Witch exception did you encountered? 你遇到过巫婆异常吗? Do u just read the char* or do you change the values? 你刚读过char *还是更改了值? if you change, you should redesign your code. 如果你改变了,你应该重新设计你的代码。

const char* test = string.c_str(); Does not create a deep copy of string, only a pointer to the internal data representation of string.data(). 不创建字符串的深层副本,只是指向string.data()的内部数据表示的指针。

=> (a suggestion) find a C++ book where you can get a more in deep view of c++. =>(一个建议)找到一本C ++书籍,你可以从中深入了解c ++。 Or something like to C++. 或类似于C ++。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM