Roman Postanciuc
Roman Postanciuc

Reputation: 5

Adding an entry to std::map in a while loop overwrites last entered pair

The problem: I am adding entries to a map in a while loop, and each time it starts at the same point, i. e. previously entered entry is dismissed/overwritten.

The code:

#include <iostream>
#include <map>

int main(){
    char* key=new char;
    char *name, *address;
    name=new char[80];
    address=new char[80];
    std::map<char*, char*> addressBook;
    while(true){
        std::cout<<"Please select action: \n";
        std::cout<<"e - exit\n";
        std::cout<<"a - add new address\n";
        std::cout<<"p - print address book\n";
        std::cin>>key;
        switch(key[0]){
            case 'a':
                std::cin>>name>>address;
                std::cin.clear();
                std::cin.ignore(500,'\n');
                addressBook[name]=address;
                std::cout<<addressBook.size()<<"\n";
                break;
            case 'p':
                for(std::map<char*,char*>::iterator it = addressBook.begin();it!=addressBook.end(); ++it)
                    std::cout<<it->first<<" "<<it->second<<"\n";
                break;
            default:
                return 0;
        }
    }
}

The setup: Code::Blocks with MinGW/gcc 4.7.1

Upvotes: 0

Views: 82

Answers (2)

Claudiu
Claudiu

Reputation: 229581

You're only storing the char * in the map (the pointer), not the value of the pointer. The same pointer keeps getting stored over and over again, and the user input is just changing what is pointed to.

You really want to be having a std::map<std::string, std::string>, instead, and to read into std::strings, not char *s. A rule of thumb is, in modern C++, you should almost never have to use new.

Upvotes: 3

Jacobr365
Jacobr365

Reputation: 846

Use the insert method found Here. As stated the way you are doing it just overwrites the last key.

Upvotes: 0

Related Questions