【问题标题】:Creating variables using input from a file [duplicate]使用来自文件的输入创建变量[重复]
【发布时间】:2013-05-27 01:40:34
【问题描述】:

我希望有人可以帮助我。

我有一个文件,其中列出了许多可以重复的城市。例如:

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

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

谢谢

【问题讨论】:

标签: c++ class visual-c++ pointers variable-assignment


【解决方案1】:

因为您只想列出城市一次,但它们可能会在文件中出现多次,所以使用 setunordered_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";    

【讨论】:

  • 谢谢大家,谢谢托尼。我现在明白了,我将使用一套,因为我不希望城市重复......你们非常有帮助。非常感谢
  • @user2419831:一件事 - 你需要在 City 类中使​​用 bool operator&lt;(const City&amp; rhs) { ... } 函数来告诉 std::set 如何比较 Citys - 它可能只是 return city_name_ &lt; rhs.city_name_; 其中@987654328 @ 是您所称的具有该含义的数据成员。
【解决方案2】:

您应该使用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));
}

【讨论】:

  • 反射对于这个要求有什么潜在用途?
  • @TonyD 我想他是在要求通过文件中的文本创建一个变量名。
  • 啊,是的 - “City* lima = ...” - 谢谢 - 我没注意。
猜你喜欢
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2013-04-19
  • 1970-01-01
  • 2019-03-09
  • 2012-09-13
相关资源
最近更新 更多