0

I hope somebody can help me.

I have a file with a list of lots of cities that can be repeated. For example:

Lima, Peru

Rome, Italy

Madrid, Spain

Lima, Peru

I have created a class City with a constructor City( string cityName )

In the main, I want to create a pointer with each city, like:

City* lima = new City( City("Lima, Peru"); 

City* rome = new City( City("Rome, Italy");

is there a way to do this with a loop reading lines from the text, like:

City* cities = new City[];
int i = 0;
while( Not end of the file )
{
   if( read line from the file hasn't been read before )
     cities[i] =  City(read line from the file);   
}

Is there a way, or I have to do it manually for each one. Any suggestions?

Thanks

2

2 Answers 2

1

Because you want to list cities just once, but they might appear many times in the file, it makes sense to use a set or unordered_set so that insert only works the first time....

std::set<City> cities;
if (std::ifstream in("cities.txt"))
    for (std::string line; getline(in, line); )
        cities.insert(City(line));  // fails if city already known - who cares?
else
    std::cerr << "unable to open input file\n";    
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks everybody and thanks Tony . I get it now, I will use a set since I don't want cities to ne repeated ....you guys are very helpful. Thanks a lot
@user2419831: one thing - you'll need a bool operator<(const City& rhs) { ... } function in your City class to tell std::set how to compare Citys - it can probably just return city_name_ < rhs.city_name_; where city_name_ is whatever you've called the data member with that meaning.
0

You should use a std::vector of City objects to store the instances. And getline should suffice for this situation:

std::vector<City> v;
std::fstream out("out.txt"); // your txt file

for (std::string str; std::getline(out, str);)
{
    v.push_back(City(str));
}

3 Comments

What potential use would reflection be for this requirement?
@TonyD I'm thinking he's asking to make a variable name by the text inside the file.
Ahh yes - "City* lima = ..." - thanks - I'd not paid attention to that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.