本文介绍了将c_str()存储为char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将函数与以下声明一起使用: extern int stem(struct stemmer * z,char * b,int k)1

I'm trying to use the function with the following declaration:extern int stem(struct stemmer * z, char * b, int k)1

我正在尝试向其传递C ++字符串,所以我认为我会使用 c_str()函数.它返回 const char * .当我尝试将其传递给 stem()函数时,出现以下错误: error:从'const char *'到'char *'[-fpermissive] .

I'm trying to pass a C++ string to it, so I thought I'd use the c_str() function. It returns const char *. When I try to pass it to the stem() function, I get this error: error: invalid conversion from 'const char*' to 'char*' [-fpermissive].

如何存储c_str()的结果,以便可以将其与 stem 函数一起使用?

How can I store the result of c_str() such that I can use it with the stem function?

这是我正在运行的代码:

Here is the code I'm running:

    struct stemmer * z = create_stemmer();
    char * b = s.c_str();
    int res = stem(z, b, s.length()); //this doesn't work
    free_stemmer(z);
    return s.substr(0,res);

推荐答案

您遇到的问题是 c_str()返回了无法修改的缓冲区( const ),而 stem()可能会修改您传入的缓冲区(不是 const ).您应该复制 c_str()的结果以获取可修改的缓冲区.

The problem you are having is that c_str() returns a buffer that can not be modified (const), while stem() may modify the buffer you pass in (not const). You should make a copy of the result of c_str() to get a modifiable buffer.

页面 http://www.cplusplus.com/reference/string/string/c_str/有关C ++ 98和11版本的更多信息.他们建议用以下内容替换 char * b = s.c_str(); :

The page http://www.cplusplus.com/reference/string/string/c_str/ has more information on the C++ 98 and 11 versions. They suggest replacing char * b = s.c_str(); with the following:

char * b = new char [s.length()+1];
std::strcpy (b, s.c_str());

这篇关于将c_str()存储为char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 22:53