0

我希望有人能帮助我。

我有一个包含许多可以重复的城市列表的文件。例如:

Lima, Peru

Rome, Italy

Madrid, Spain

Lima, Peru

我创建了一个带有构造函数 City( string cityName ) 的类 City

总的来说,我想为每个城市创建一个指针,例如:

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

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

有没有办法通过循环读取文本中的行来做到这一点,例如:

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);   
}

有没有办法,或者我必须为每个人手动完成。有什么建议么?

谢谢

4

2 回答 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";    
于 2013-05-27T02:08:45.500 回答
0

您应该使用对象std::vectorCity存储实例。并且getline应该足以应对这种情况:

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));
}
于 2013-05-27T01:44:50.290 回答