Phi
Phi

Reputation: 335

Getting ifstream to read ints from a file into a map C++

I cannot seem to get my file "paths.txt" to read into my map file. I cannot figure out what I am doing wrong. I'd appreciate any pointers. The end result I want is to take each of the key value pairs into the map.

The format of my file is

192, 16 120, 134 256, 87 122, 167 142, 97 157, 130 245, 232 223, 63 107, 217 36, 63 206, 179 246, 8 91, 178

And my code is

ifstream myfile("paths.txt"); 
    std::map<int, int> mymap;
    int a, b;
    while (myfile.good())
    {
    myfile >> a >> b;
    mymap[a] = b;
    }
    mymap;

Upvotes: 1

Views: 829

Answers (1)

R Sahu
R Sahu

Reputation: 206717

  1. You don't have anything to read the commas in your text file.
  2. Also , instead of while (myfile.good()), use while ( myfile >> ...).
std::map<int, int> mymap;

char dummy;
int a, b;
while (myfile >> a >> dummy >> b)
{
   mymap[a] = b;
}

Upvotes: 2

Related Questions