Reading in and initializind data from file

Im familiar with fstream and know how to read in data, given that there is
one type per line.
But I have a file that has multiple lines each containing a string (an address) and two double values (latitude and longitude).

Can anyone help with the logic part of reading in data and initializing them to member variable.
#include <fstream>
#include <iostream>
#include <sstream>

int main()
{
using namespace std;
ifstream fstrm("sample.txt", ios::in);
//Read a line into the file
string line , word;
while(getline(fstrm,line))
{
cout << "Line:" << line <<endl;
//do per line processing
istringstream istrm(line);
string sCountry; double dlat , dlong;
istrm >> sCountry>> dlat >> dlong ;
cout << "Country:" << sCountry << " LAT:" << dlat << " LONG:" << dlong <<endl;
//do further processing
}
}

OUTPUT
$ cat sample.txt
INDIA 21.00 78.00
AUSTRALIA 35.30 149.12

$ ./out
Line:INDIA 21.00 78.00
Country:INDIA LAT:21 LONG:78
Line:AUSTRALIA 35.30 149.12
Country:AUSTRALIA LAT:35.3 LONG:149.12

//////////////////////////////////////////////////////////
Another simple method

$ cat test1.cpp
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

struct CountryMap
{
char sCountry[20];
double dlat;
double dlong;
};
int main()
{
ifstream fstrm("sample.txt");
CountryMap cmap;
if(fstrm.is_open())
while( fstrm>>cmap.sCountry>>cmap.dlat>>cmap.dlong )
{
cout << "Retrieved Country[" << cmap.sCountry << "]Latitude[" <<cmap.dlat << "]Longitude["<<cmap.dlong<<"]\n";
//do what you like here with place, latitude, longitude. Store to a vector<CountryMap> if you like for further processing....

}

fstrm.close();
fstrm.clear();
}

OUTPUT
----------
for the same sample.txt above
$ ./out
Retrieved Country[INDIA]Latitude[21]Longitude[78]
Retrieved Country[AUSTRALIA]Latitude[35.3]Longitude[149.12]

Last edited on
Topic archived. No new replies allowed.