Chris.Frog Chris.Frog - 1 year ago 67
C++ Question

sf::String put into std::map key doesn't work - the vaule is not saved into map

as I wrote in the topic - I try to put sf::String into map first argument and it does not work. Here's the code:

void Flashcards::add(sf::String sf_string) {
std::string text = sf_string.toAnsiString();
std::pair<std::string,std::string> pairr = std::make_pair(text,"<Polish translation>");
std::cout << "Inserting: " << pairr.first << std::endl;
all_words.insert(pairr); //std::map<std::string, std::string> variable

void Flashcards::show() {
std::cout << "Flashcards:\n";
for (std::map<std::string, std::string>::iterator it = all_words.begin(); it != all_words.end(); it++)
std::cout << "English word: " << it->first
<< " " << "Polish word: " << it->second << std::endl;

The result in console is:

Inserting: //a word//
Polish word: <Polish translation>

Instead of needed:

Inserting: hello
English word: //a word// Polish word: <Polish translation>

Here are the variations I have already tried:

1) I switched the arguments so it looked like this:
std::make_pair("<Polish translation>",text);
and it works - hardcoded key and the value are both showed in the console (but I don't want hardcoding, what is obvious).

2) Note that this line:
std::cout << "Inserting: " << pairr.first << std::endl;
shows that the key value is converted into std::string correctly - calling this will show value we have just typed on the keyboard.

3) I tried to send the sf::String value directly to the std::make_pair() method, it works exactly the same as putting std::string there.

Can somebody say how to make this work?

Answer Source

The string you are providing as an argument to the add method obviously ends with a \r (carriage return) character, probably because you are reading it from a Windows text file using a Unix/Linux execution environment. If you capture the output of your program in a file and look at it with a hexdumper (such as hd), you should immediately see what is going on.

It certainly has nothing to do with your use of the C++ standard library. However, you don't need to go to all that work to insert an entry into a std::map. Just do this:

all_words[key] = value;

As long as key has the right type (or there is an automatic conversion), that will do precisely what you want in a single line easily-understood line, and probably more efficiently as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download