【发布时间】:2018-04-09 12:53:58
【问题描述】:
嗨,我一直在努力让我的迭代器指针找到 map stl 容器的指定键。以下项目用于我的解析器练习,我们得到一个文件,重点是解析它并逐行读取。该文件应该位于要读取的项目文件夹中。 该文件具有以下文本
[settings]
;this is the settings section
fullscreen = true
gamepad = false
windowWidth = 800
windowHeight = 600
[levels]
numLevels = 3
Level1 = file1.lvl
Level2= file2.lvl
Level3=file3.lvl
[player]
name = Student
speed = 5.0
[enemy]
name ="Zombie"
speed = 1.0
我们应该创建一个 Mapkey,它是部分(括号中的文本)和“|”的组合和key(即=之前的文本),value是等号之后的文本。
在我尝试使用 find 函数查找指定的 Mapkey 之前,我的代码可以正常工作。有人可以帮忙吗?
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
std::map<std::string, std::string> m_mapPairs;
int main()
{
string strLine;
fstream myFile;
myFile.open("New Text Document.txt"); //name of the file to be read
if (myFile.is_open())
{
static string section = " ";
string key = " ";
string value= " ";
while (!myFile.eof())
{
getline(myFile, strLine);
if (strLine.find("[") !=-1)
{
int index1 = strLine.find_first_of("["); //finds it in a line, if it does it puts it in index 1 if it doesnt it doesnt bother
int index2 = strLine.find_first_of("]");//finds it in a line, if it does it puts it in index 2 if it doesnt it doesnt bother
section = strLine.substr(index1 + 1, index2 - 1);
section = section + "|";
}
if (strLine.find("=") != -1)
{
int index1 = strLine.find("");
int index2 = strLine.find("=");
key = strLine.substr(index1, index2 );
}
if (strLine.find("=")!=-1 )
{
int index1 = strLine.find("="); //finds it in a line, if it does it puts it in index 1 if it doesnt it doesnt bother
value = strLine.substr(index1+1 , 11);
}
if (strLine.find(";") > -1)
{
int index1 = strLine.find(";"); //finds it in a line, if it does it puts it in index 1 if it doesnt it doesnt bother
string ivalue = strLine.substr(index1 + 1, 11);
}
if (key != "") {
std::string Thekey = section + key;
m_mapPairs.insert(std::pair<std::string, std::string>(Thekey, value));
}
}
std::map<std::string, std::string>::iterator iter; //iterating through all the keys
iter = m_mapPairs.begin();
while (iter != m_mapPairs.end())
{
std::cout << iter->first << "\'s value is ";
std::cout << iter->second << std::endl;
iter++;
}
iter = m_mapPairs.find("settings|windowWidth"); //trying to find this key in the map but cant find it
if (iter != m_mapPairs.end())
{
std::cout << "found: " << std::endl;
return true;
}
else
{
return false;
}
myFile.close();
}
int a;
std::cin >> a;
return (0);
}
如果有任何帮助,我将不胜感激。 谢谢
【问题讨论】:
-
不是问题,但
static string section = " ";可以是string section; -
与您的问题更相关,您能否尝试向我们展示输入文件的较小部分,然后显示您的程序的预期输出和实际输出(使用较小的输入集)?你试过to debug your program?
-
看起来问题是您在创建的字符串的末尾留下了试用空格。使用调试器单步执行您的代码以进行确认。如果您是,您将需要编写一个修剪函数或更改解析行的方式。
-
@Someprogrammerdude 嘿,它看起来应该和 jejos 控制台上的东西一模一样。
标签: c++ dictionary stl find containers