我正在尝试创建一个加载一组代表菜单的数据的函数。该文件的布局如下所示:
DS测试菜单
6
MENU"开始" " play.mnu"
MENU"选项" " opt.mnu"
MENU"帮助" " help.mnu"
选项"数据结构项目1B"
OPTION" Full Sail"
选项"游戏设计与开发"
第一行是菜单的标题,第二行是菜单项的数量。 后面的每一行都是该菜单上的一个项目。提取引号中的每个菜单项的名称时出现问题。
以下是我的尝试:
ifstream fin;
fin.open(filepath.c_str(), ios_base::in);
if (fin.is_open())
{
getline(fin, this->title);
int numMenuItems;
fin >> numMenuItems;
for (size_t i = 0; i < numMenuItems; i++)
{
menuItem temp;
string menutitle;
fin >> menutitle;
if (menutitle == "MENU")
{
string name, filepath;
fin >> name;
fin >> filepath;
name = name.substr(1, name.length() - 2);
filepath = filepath.substr(1, filepath.length() - 2);
temp.is_subMenu = true;
temp.name = name;
temp.subMenuPath = filepath;
}
else
{
string name;
fin >> name;
name = name.substr(1, name.length() - 2);
temp.is_subMenu = false;
temp.name = name;
}
}
}
这适用于前3个菜单项,当引号中菜单项的名称长几个字时,我的问题出现了。我知道这是因为使用提取运算符只会提取直到第一个空格。我还必须使用字符串substr方法来丢失引号。
我不确定提取数据和忽略引号的更好方法,我无法更改数据存储的格式。
提取此信息的最佳方式是什么?
答案 0 :(得分:1)
感谢@BenVoigt,我能够让它发挥作用。
if (fin.is_open())
{
getline(fin, this->title);
int numMenuItems;
fin >> numMenuItems;
for (int i = 0; i < numMenuItems; i++)
{
menuItem temp;
string tempshit;
fin >> tempshit;
if (tempshit == "MENU")
{
string name, filepath, temp2;
getline(fin, temp2, '"');
getline(fin, name, '"');
getline(fin, temp2, '"');
getline(fin, filepath, '"');
temp.is_subMenu = true;
temp.name = name;
temp.subMenuPath = filepath;
}
else
{
string name, temp2;
getline(fin, temp2, '"');
getline(fin, name, '"');
temp.is_subMenu = false;
temp.name = name;
}
}
}