Reading Input File

I am to read in a road map of interconnected cities and their corresponding distances as part of an assignment. The file has format like 'source city, destination city, distance between the two cities.' However, my code below does reads all of the source cities, but does not properly add all neighboring cities (i.e. not all city pairs are read in). Hope this makes sense and any help is much appreciated!


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
  City tempCity;
	City lastCity;
	vector<Neighbor> tempNeighbors;
	Neighbor tempNeighbor;

	while (!myfile.eof())
	{
		myfile >> tempCity.name;
		if (tempCity.name == "END")
		{
			lastCity.neighbors = tempNeighbors;
			cities.push_back(lastCity);
			break;
		}
		myfile >> tempNeighbor.name;
		myfile >> tempNeighbor.distance;
		if (lastCity.name != tempCity.name)
		{
			if (lastCity.name != "")
			{
				lastCity.neighbors = tempNeighbors;
				cities.push_back(lastCity);
				tempNeighbors.clear();
			}
		}
		lastCity = tempCity;
		tempNeighbors.push_back(tempNeighbor);
Sample source file:
New York, Boston, 190
Chicago, Milwaukee, 83

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
#include <iostream>
#include <string>
#include <fstream>
#include <vector>

struct City
{
    std::string m_name;
    std::string m_neighbor;
    double m_distance;
};
std::ostream& operator << (std::ostream& os, const City& c)
{
    os << c.m_name << " " << c.m_neighbor << " " << c.m_distance << '\n';
    return os;
}
int main()
{
    std::ifstream inFile("D:\\input1.txt");
    std::vector<City> cities;
    if(inFile)
    {
        City c;
        while(getline(inFile,c.m_name,',')
              && getline(inFile, c.m_neighbor, ',')
                && inFile >> c.m_distance)
        if(inFile)
        {
            cities.push_back(c);
        }
    }
    for (const auto& elem : cities)
    {
        std::cout << elem;
    }
}

Thank you for your response gunnerfunner. Take for example the source file is:
New York, Boston, 190
Boston, Chicago, 50
Chicago, Milwaukee, 83
I am trying to get my code to show that neighbors of, say Boston, are New York and Chicago, instead of just Chicago. This is the specific part I am having trouble with, sorry if I wasn't overly specific earlier.
closed account (48T7M4Gy)
@Peanut373
You need to structure your data in a different way.

Create a 'connectivity array' as you read in the data. The array comprises rows and columns corresponding to the cities with the intersection of a row and column being the distance between the two cities.

Keep in mind the array is symmetrical.

Neighbours are simply cities with a non-zero entry in the array for a particular row (or column).
closed account (48T7M4Gy)
http://www.cplusplus.com/forum/beginner/208396/#msg981999
Topic archived. No new replies allowed.