简体   繁体   中英

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;
  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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM