首页 > 解决方案 > C ++在while循环中读取2行到地图?

问题描述

所以我有一个文本文件,其格式为一行的键和下一行的值。我是 C++ 新手,我很难找到一种方法将这两行读入变量并在映射中分配它们。

所以我打开的文本文件格式如下:

中国
亚洲
加拿大
北美
埃及
非洲
ETC...

我正在尝试使用 while 循环遍历这些行,以将中国分配为键,将亚洲作为值,然后分配给加拿大和北美等。我现在写了一些不起作用的代码,因为我不知道如何迭代这些行。非常感谢任何建议,特别是因为我知道这可能是一个愚蠢的问题,我只是在网上找不到任何真正回答这个问题的东西。

CountryCatalogue::CountryCatalogue(std::string continentFileName, std::string countryFileName)
{
    std::ifstream continentFile(continentFileName);
    std::ifstream countryFile(countryFileName);
    std::string line;
    std::map<std::string, std::string> mymap;

    if (continentFile.is_open()) {
        while (std::getline(continentFile, line)) {
            mymap[line] = ??????
        }
        continentFile.close();
    }

标签: c++fileio

解决方案


只需调用std::getline在地图中定位正确的键:

// rest of code omitted
while (std::getline(continentFile, line)) {
    std::getline(continentFile, mymap[line]);
}

这是有效的,因为mymap[line]使用默认构造函数自动激活值并返回对 new 的引用string,然后可以通过引用将其传递给getline.

要处理没有值的键的可能性,您可能需要测试两个getlines,例如:

// rest of code omitted
while (std::getline(continentFile, line)) {
    if (!std::getline(continentFile, mymap[line])) {
        // Mismatch between keys and values, maybe emit warning
        mymap.erase(line); // Remove key which lacked value
        break; // Exhausted file
    }
}

推荐阅读