Read Source/Destination City Pairs from File

In a sample .txt file to be read in for a uniform cost search program, the first city in a line is the source, followed by the destination city, and finally the distance between the two cities.

The issue I am having is I do not know how I could read in all cities and respective neighboring cities. A sample of input data is below. I appreciate any help/ideas!

Luebeck Hamburg 63
Hamburg Bremen 116
Hamburg Hannover 153
Hamburg Berlin 291
Bremen Hannover 132
Bremen Dortmund 234

Last edited on
You could store the data in a struct and store the structs in a vector.

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
44
45
46
47
48
49
50
#include <iostream>
#include <fstream>
#include <string>
#include <vector>


using namespace std;

struct Connection
{
  string source;
  string destination;
  int distance;
};

istream& operator >> (istream& is, Connection& conn)
{
  is >> conn.source >> conn.destination >> conn.distance;

  return is;
}

ostream& operator << (ostream& os, const Connection& conn)
{
  os << conn.source << "\t"  << conn.destination << "\t" << conn.distance << "\n";

  return os;
}
int main() 
{
  ifstream  src("cities.txt");

  if (!src)
  {
    // handle / display error
    return -1;
  }
  vector<Connection> connections;

  for (Connection conn; src >> conn;)
    connections.push_back(conn);

  // check that everything was read correctly

  for (const Connection& conn : connections)
    cout << conn;

  system("pause");
  return 0;
}
Thank you for your reply, Thomas! Would it be possible to perform a search algorithm on the vector of Connections as it is in this state? Is it not necessary to, for example, create a vector of a new class City with each City having a vector of neighbor Cities and their respective distances?
Last edited on
closed account (48T7M4Gy)
http://www.cplusplus.com/forum/beginner/208328/#msg981854
Topic archived. No new replies allowed.