我希望有人能帮助我。
我有一个文件,其中包含许多可以重复的城市列表。例如:
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);
}有没有办法,或者我必须手动完成每一个。有什么建议吗?
谢谢
发布于 2013-05-27 10:08:46
因为您只想列出一次城市,但它们可能会在文件中出现多次,所以使用set或unordered_set以便只在第一次插入时才起作用是有意义的。
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-27 09:44:50
您应该使用City对象的std::vector来存储实例。对于这种情况,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));
}https://stackoverflow.com/questions/16765356
复制相似问题