c++ - 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();
}
解决方案
只需调用std::getline
在地图中定位正确的键:
// rest of code omitted
while (std::getline(continentFile, line)) {
std::getline(continentFile, mymap[line]);
}
这是有效的,因为mymap[line]
使用默认构造函数自动激活值并返回对 new 的引用string
,然后可以通过引用将其传递给getline
.
要处理没有值的键的可能性,您可能需要测试两个getline
s,例如:
// 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
}
}
推荐阅读
- c# - 为什么我的对象列表呈现为复选框返回一个空列表?[ASP.NET 核心 - 3.1]
- kubernetes - Kubernetes:使用“envFrom”定义依赖于其他变量的环境变量
- android - 我在颤振代码中有问题。它的给定是 RenderCustomMultiChildLayoutBox 对象在布局期间被赋予了无限的大小
- java - 如何将数组的 JSON 数组添加到模型中
- python - 如何设置整行而不是所有单元格的样式
- github-pages - 如何让 GIF 出现在 Github Pages 帖子上?
- c# - 使用 C# 类完全定义的 Razor 组件的 CSS 隔离
- arrays - 如何对数组求和的循环进行矢量化?
- java - spring boot CLIENT_PLUGIN_AUTH 是必需的,检查mysql版本
- r - 尽管发出 purrr 的“否则”错误 - 为什么没有触发 purrr/可能的“否则”?