Read key value pairs in a file and input into a map.

I need to input data from a file that looks like this:
Asdf 1200
Qwer 4000
Zxcv 3400
Zser 29564

I (think?) I need it in a map container because they are key value pairs. Most of the examples I've found on the Internet say to just use a while loop but I can't get any of those incantations to work. I've also seen copy used in examples, but I don't understand how that works.

This doesn't work:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <fstream>
#include <map>

using namespace std;

string here_document = \
R"EOF(Medium Speed
Air 1100
Water 4900
Steel 16400
Copper 7500
Nylon 1150
Iron 8200
)EOF";

int main(int argc, const char * argv[]) {

    ofstream file_out;
    file_out.open("data.txt");
    file_out << here_document;
    here_document.clear();
    file_out.flush();
    file_out.close();

    std::ifstream file_in("data.txt");
    
    cout << file_in.rdbuf(); // debug
    
    string key;
    int value;
    map<string, int> my_map;

    while (getline(file_in, key) && getline(file_in, value)){
        cout << "Debug: " << key << value << endl; // No output!?!?
        my_map[key] = value;
    }

    remove("data.txt");
    file_in.close();

    return 0;
}
Last edited on
Your program appears to be having compiler errors rather than run-time errors.
while (getline(file_in, key) && getline(file_in, value)){

The simpler code would be :
1
2
3
4
while (getline(file_in, key)){
        cout << "Debug: " << key << endl;
        my_map[key] = value;
    }

Last edited on
Well, to optimally read the input file, you would need something like this :
1
2
3
4
while (file_in >> key && file_in >> value){
        cout << "Read: " << key << " " << value << endl;
        my_map[key] = value;
    }
Topic archived. No new replies allowed.