c++ - 使用来自文件的输入创建变量

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

<分区>

我希望有人能帮助我。

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

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

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

谢谢

最佳答案

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

关于c++ - 使用来自文件的输入创建变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16765356/

相关文章:

c++ - 在库中公开 constexpr 专用模板函数

c++ - 根据模板参数不等式执行不同的功能

c++ - 在整数 std::chrono::durations 之间转换

c++ - 使用全局引用调用函数时发生访问冲突

c++ - 将字符串文字转换为 std::array 的函数模板

java - 处理大类

java - 避免处理 config.properties 的 Java 类文件中的静态方法和变量

php - 定义前的实例化类

Windows 结构的 C++

c++ - 我怎样才能访问派生类的私有(private)方法?