How to pull data from txt file and put into a sturucture

Dec 6, 2015 at 4:42pm
Hi i'm really new to c++ so bare with. I am looking pull data from a text file that displays multiple cities in the format cityname xcoordinate ycoordinate and then displays them. For some reason though the program only displays the last cities data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <vector>
#include <cmath>

struct City {
    string name;
    int x, y;
};

int main()
{
    ifstream inputFile("CoordinateData.txt");
    vector<City> cities;
    City temp;
    while (inputFile >> temp.name >> temp.x >> temp.y)
        cities.push_back(temp);

    City anchor; // the constant data.
    for (City city : cities)
    cout << temp.name << temp.x << temp.y << endl;
    system("pause");
    return(0);
}
Last edited on Dec 6, 2015 at 4:46pm
Dec 6, 2015 at 5:04pm
Line 19 temp.name should be city.name etc.

If you rewrite the while loop like this, the temp variable will not exist after that loop, avoiding its accidental reuse.
1
2
    for (City temp; inputFile >> temp.name >> temp.x >> temp.y; )
        cities.push_back(temp);

I'm not sure whether I like that style or not, but it's a thought.
Last edited on Dec 6, 2015 at 5:08pm
Dec 6, 2015 at 5:08pm
Thanks! Do you know how I'd then go about just displaying a specific city?
Dec 6, 2015 at 5:13pm
Do you know how I'd then go about just displaying a specific city?

How specific? The nth one in the vector, or the one with a particular name or ...
Dec 6, 2015 at 5:23pm
What I need to do in the long run is be able to select a few of the cities and use their coordinates in calculations so i'm wondering how I would be able to select an individual city if i needed to use it. I'm not to sure which would be easier either one would be helpful.
Dec 6, 2015 at 5:50pm
Select by number is straightforward, just use the array syntax cities[n] where n is in the range 0 to cities.size()-1.
http://www.cplusplus.com/reference/vector/vector/operator%5B%5D/
http://www.cplusplus.com/reference/vector/vector/size/

Select by name, you could write your own code to search the vector, or use the std::find from the <algorithm> header.
http://www.cplusplus.com/reference/algorithm/find/
Last edited on Dec 6, 2015 at 6:05pm
Dec 6, 2015 at 7:37pm
when selecting a city using the syntax array [n] eg city.name[1] it only gives a letter of the second character of the city rather than the second word in the list. Any ideas why this might be?
Dec 6, 2015 at 8:04pm
Your vector is called cities. So you would need to access cities[1].name.

Example:
1
2
3
4
5
    unsigned int n = 3;
    if (n < cities.size())
        cout << "cities[" << n << "] " << cities[n].name << "  " << cities[n].x << "  " << cities[n].y <<  '\n';
    else
        cout << "Out of range: " << n << "  max: " << cities.size()-1   <<  '\n';

Topic archived. No new replies allowed.