Variables in TXT

So I posed this question earlier but maybe I didn't explain it well enough. Basically, I have a txt file with pairs of coordinates for different locations. The first column has latitudes and the second longitudes. It looks a bit like this:
23.64 78.98
21.34 34.67
21.11 57.52
and so on and so on.. Basically, what I need to do is assign a variable for each latitude and longitude (separately) so that later on, I'll be able perform distance calculations with them. How could I pull the data from this txt (titled coordinates.txt) to c++, and make it so that the variable a1, for example, equals 23.64, a2 = 78.98, b1 = 21.34 etc. I don't really care what the variables will be called, just need there to be a variable for each number. I'm quite inexperienced in c++ and have little time to learn it so any help would be greatly appreciated.
Use some container and store there file data.
How would I do this? I know that there are arrays, vectors, etc., but like I said, I am incredibly inexperienced.
1
2
3
4
5
6
7
8
9
10
#include <vector>
#include <string>
#include <sstream>
#include <fstream>

struct Coordinate
{
    double lat;
    double lon;
};


1
2
3
4
5
6
7
8
9
10
11
12
13
typedef std::vector<Coordinate> Coordinates;

Coordinates coordinates;
std::istream fin("coords.txt");
std::string line;

while (std::getline(fin, line))
{
    std::stringstream iss(line);
    Coordinate coord;
    iss >> coord.lat >> coord.lon;    
    coordinates.push_back(coord);
}


Then access it like so:
1
2
3
4
5
for (Coordinates::iterator it = coordinates.begin(); it != coordinates.end; ++it)
{
    it->lat; // This is the latitude
    it->lon; // This is the longitude
}
Last edited on
I keep getting an error in the 1st line of the accessing. Maybe I'm not putting this in the right place, what would this whole code look like? Seriously, I just started c++ a few days ago so this is all very new. Thanks
I fixed a couple of minor errors in Stewbond's code.
(added main, changed istream to ifstream, added () to end).

This compiles cleanly:
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
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <iostream>
using namespace std;

struct Coordinate
{   double lat;
    double lon;
}; 

typedef vector<Coordinate> Coordinates;

int main ()
{   Coordinates coordinates;
    ifstream fin ("coords.txt");
    string line;

    while (getline(fin, line))
    {   stringstream iss(line);
        Coordinate coord;
        iss >> coord.lat >> coord.lon;    
        coordinates.push_back(coord);
    }
    for (Coordinates::iterator it = coordinates.begin(); it != coordinates.end(); ++it)
    {  cout << "Lat=" << it->lat << endl;
       cout << "Lon=" << it->lon << endl; 
    }
}

Topic archived. No new replies allowed.