dimanche 19 mars 2017

Read data from the file and insert into map C++

When I request the key, it gives the a huge negative (-7998482842) or positive (898395893) number, but it should give back a string.

file format: string string hello@gmail.com hello@hotmail.com

I think the problem is here: table[name] = std::string(color);

Can someone pls help

class table_data
{
   public:
    std::map<std::string, std::string> table;

   bool read(std::string &fname)
   {
    std::ifstream ifs (fname, std::ifstream::in);
    if(ifs.fail())
    {
        printf("Cant open\n");
        return false;
    }
    return read(ifs);
}
bool read(std::istream &is)
{
    for (std::string line; std::getline(is, line);)
    {
        char *name = strtok(const_cast<char*>(line.c_str()), " \r");

        if(name != nullptr)
        {
            char *color = strtok(nullptr, " ");
            if(color != nullptr)
            {
                table[name] = std::string(color);
            }
            else
            {
                printf("No data %s\n", line.c_str());
                return false;
            }
        }
        else
        {
            printf("No name\n");
            return false;
        }
    }

    return true;
   }
std::string getcolor(std::string name)
{
    std::map<std::string, std::string>::iterator it;
    it = table.find(name);
    if (it != table.end())
    {
        return it->second;
    }

   }
};

Aucun commentaire:

Enregistrer un commentaire