替换字符串时出现编译错误

Getting compilation error while replacing a string

本文关键字:编译 错误 字符串 替换      更新时间:2023-10-16

我创建了一个 Url 编码器类,其工作是编码或解码 Url。

为了存储特殊字符,我使用了地图std::map<std::string, std::string> reserved

我已经像这样初始化了地图this->reserved["!"] = ":)";

为了读取给定字符串中的字符,我正在使用迭代器for(string::iterator it=input.begin(); it!=input.end(); ++it)

现在,当我尝试使用替换函数替换特殊字符时encodeUrl.replace(position, 1, this->reserved[*it]);

我收到以下错误

url.cpp: 在成员函数 'std::string url::url::

UrlEncode(std::string('中:
Url.cpp:69:54:错误:从"char"到"const char*"的转换无效 [-fallowive]
/usr/include/c++/4.6/bits/basic_string.tcc:214:5:错误:初始化参数 'std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&( [使用 _CharT = char, _Traits = std::char_traits, _Alloc = std::allocator]' [-fpermissive]

我不确定代码有什么问题。这是我的函数

string Url::UrlEncode(string input){
    short position = 0;
    string encodeUrl = input;
    for(string::iterator it=input.begin(); it!=input.end(); ++it){
        unsigned found = this->reservedChars.find(*it);
        if(found != string::npos){
            encodeUrl.replace(position, 1, this->reserved[*it]);
        }
        position++;
    }
    return encodeUrl;
}

好吧,解决方案中的错误是您尝试传递单个字符而不是std::string或 c 样式的 0 终止字符串 ( const char * ( 来映射。

std::string::iterator一次迭代一个字符,因此您可能需要使用 std::map< char, std::string >

it是字符的迭代器(它的类型std::string::iterator(。因此,*it是一个角色。

你正在做reserved[*it],并且由于你给reserved的类型(std::map<std::string, std::string>(,下标运算符期望一个string,而不是一个char

然后编译器尝试从charstd::string的用户定义转换,但是没有接受charstring构造函数。有一个接受char const*(见这里(,但编译器无法将char转换为char const*;因此,错误。

另请注意,您不应该对 string::find() 返回的值使用 unsigned,而应该使用 string::size_type

看起来 *it 的类型与什么不匹配

 reservedChars.find() 

应该接受。

尝试添加

const char* pit = *it;

就在之前

unsigned found = this->reservedChars.find(*pit);
    if(found != string::npos){
        encodeUrl.replace(position, 1, this->reserved[*pit]);