File to Map with structs

Mar 27, 2017 at 1:49am
Currently trying to figure out how to read data from a file, line by line (getline) which be placed in a new Node which is initlized according to the Node constructor (see below). This should then be added to a map called map<string, Node> nodes where the string is the Node label.

Here are the structs that I have made:

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
struct Node{
  int x;
  int y;
  string label;

  Node()=default;
  Node(int i, int j, string l) :  x(i), y(j), label(l) {} ;
  string to_string () const;
  bool equal_nodes(const Node&);
  double distance(const Node &)const;
};

struct Network{
  string label;
  map<string, Node> nodes;
  vector<string> route;

  Network()=default;
  Network(ifstream &);
  string to_string () const;
  Node get_node(string);
  void put_node(Node);
  bool in_route(const Node&);
  Node closest(Node &);
  string calculate_route(const Node&, const Node&);
};


This is the function I was trying to start/do:

1
2
3
4
5
6
7
8
9
10
11
Network::Network(ifstream &) {

string label, line;
Node n;
map<string, Node> nodes;

	while (getline(fin, line)) {

	}

}


This is what is inputted in the main:
1
2
3
4
5
    string fname;
    cin >> fname;
    ifstream fin(fname);
    Network net(fin);
    Node n = net.nodes["A"];


This is the txt file I am suppose to be reading data from:

1
2
3
4
1 1 A
2 2 B
3 3 C
4 4 D


I expect the output, when I run through my function that turns the node into a string, as the following: A: (1, 1)
Last edited on Mar 27, 2017 at 1:53am
Mar 27, 2017 at 3:41am
1
2
3
4
5
6
7
8
9
10
11
12
while( std::getline( fin, line ) ) {

    std::istringstream stm(line) ; // #include <sstream>

    int x, y ;
    std::string label ;

    if( stm >> x >> y >> label ) nodes.emplace( label, Node{ x, y, label } ) ;

    // uncomment if you want to stop processing further lines after a badly formed line is encountered
    // else fin.clear( std::ios::failbit ) ;
}
Mar 27, 2017 at 5:14pm
That worked and makes sense, thanks!
Topic archived. No new replies allowed.