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

Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70
user2419831
  • 181
  • 4
  • 11
  • 1
    Not an answer, but there is something strange about how you use constructors. To create a `City` object dynamically, best use `City *lima = new City("Lima, Peru");`, not `City *lima = new City(City("Lima, Peru"));`. – jogojapan May 27 '13 at 01:53
  • See here: http://stackoverflow.com/questions/7143120/convert-string-to-variable-name-or-variable-type, http://stackoverflow.com/questions/8641751/how-to-use-a-string-as-a-variable-name-in-c, http://stackoverflow.com/questions/11183429/declare-variables-names-using-string-value-data-in-cpp-c – jogojapan May 27 '13 at 02:01

2 Answers2

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";    
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • 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 May 27 '13 at 02:47
  • @user2419831: one thing - you'll need a `bool operator<(const City& rhs) { ... }` function in your City class to tell `std::set` how to compare `City`s - it can probably just `return city_name_ < rhs.city_name_;` where `city_name_` is whatever you've called the data member with that meaning. – Tony Delroy May 27 '13 at 02:52
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));
}
David G
  • 94,763
  • 41
  • 167
  • 253