0
votes

I've created a Url Encoder class whose job is to encode or decode an Url.

For storing the special characters I've use a map std::map<std::string, std::string> reserved.

And I've initialized the map like this this->reserved["!"] = ":)";

For reading characters form a given string I'm using an iteratorfor(string::iterator it=input.begin(); it!=input.end(); ++it)

Now when I try to replace a special character using replace function encodeUrl.replace(position, 1, this->reserved[*it]);

I get the following error

Url.cpp: In member function ‘std::string Url::Url::UrlEncode(std::string)’:
Url.cpp:69:54: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]
/usr/include/c++/4.6/bits/basic_string.tcc:214:5: error: initializing argument 1 of ‘std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits, _Alloc = std::allocator]’ [-fpermissive]

I'm not sure what's wrong with the code. Here's my function

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;
}
3

3 Answers

1
votes

Well, the error in your solution is that you are trying to pass a single character rather than std::string or c-style 0-terminated string (const char *) to map.

std::string::iterator is iterating one char at a time, so you may want to use std::map< char, std::string >.

1
votes

it is an iterator of characters (it has type std::string::iterator). Thus, *it is a character.

You are doing reserved[*it], and because of the type you gave to reserved (std::map<std::string, std::string>), the subscript operator expects a string, not a char.

The compiler then tries a user-defined conversion from char to std::string, but there is no constructor of string which accepts a char. There is one that accepts a char const* though (see here), but the compiler can't convert a char to a char const*; hence, the error.

Also notice, that you should not use unsigned for the value returned by string::find(), but rather string::size_type.

0
votes

It looks like there's a mismatch between the type of *it and what

 reservedChars.find() 

is supposed to accept.

Try adding

const char* pit = *it;

right before

unsigned found = this->reservedChars.find(*pit);

    if(found != string::npos){

        encodeUrl.replace(position, 1, this->reserved[*pit]);