c++unordered-mapistringstream

Problem reading file and storing it in unordered_map


I'm trying to read a file and store it's content into an unordered_map but I've got a little problem. This is my unordered_map:

std::unordered_map<std::string, std::vector<double>> _users;

And this is the content of the file that I'm trying to read:

Mike 4 NA 8 NA NA
Lena NA 8 4 NA 9

I want to store the content in _users in a way that the key is the name, and inside the vectors we have the numbers associated to the name. Moreover I want NA to be equal to 0. So I managed to do this:

while ( std::getline(file, line))
    {
        std::istringstream iss(line);
        std::string key;
        double value;
        iss >> key;
        dict[key] = std::vector<double>();

        while (iss >> value)
        {
            dict[key].push_back(value);
        }
    }

But since value is a double, when checking NA it just stops the while loop and I just get, for example with Mike: Mike 4. How can I do in order to get it to read NA and put it as 0 inside the vector ? Thank you for your help!


Solution

  • For your inner loop, you could do:

        std::string stringval;
        while (iss >> stringval)
        {
            double value;
            try
            {
                value = std::stod (stringval);
            }
            catch (...)
            {
                value = 0.0;
            }
            dict[key].push_back(value);
        }