C++ 使用ifstream检索引号内的完整字符串
我试图创建一个函数,它加载一组表示菜单的数据。文件的布局如下所示: DS测试菜单 六, 菜单“开始”“播放.mnu” 菜单“选项”“opt.mnu” 菜单“帮助”“帮助.mnu” 选项“数据结构项目1B” 选项“全帆” 选项“游戏设计与开发” 第一行是菜单的标题,第二行是菜单项的数量。 后面的每一行都是该菜单上的一项。我的问题出现在提取引号中每个菜单项的名称时 以下是我尝试过的:C++ 使用ifstream检索引号内的完整字符串,c++,string,file-io,C++,String,File Io,我试图创建一个函数,它加载一组表示菜单的数据。文件的布局如下所示: DS测试菜单 六, 菜单“开始”“播放.mnu” 菜单“选项”“opt.mnu” 菜单“帮助”“帮助.mnu” 选项“数据结构项目1B” 选项“全帆” 选项“游戏设计与开发” 第一行是菜单的标题,第二行是菜单项的数量。 后面的每一行都是该菜单上的一项。我的问题出现在提取引号中每个菜单项的名称时 以下是我尝试过的: ifstream fin; fin.open(filepath.c_str(), ios_base::in); i
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;
}
}
}
ifstream-fin;
打开(filepath.c_str(),ios_base::in);
如果(fin.is_open())
{
getline(fin,this->title);
整数项;
fin>>数量项目;
对于(大小i=0;i>菜单项;
如果(菜单项==“菜单”)
{
字符串名称,文件路径;
fin>>名称;
fin>>文件路径;
name=name.substr(1,name.length()-2);
filepath=filepath.substr(1,filepath.length()-2);
temp.is_子菜单=真;
temp.name=名称;
temp.subnumpath=文件路径;
}
其他的
{
字符串名;
fin>>名称;
name=name.substr(1,name.length()-2);
temp.is_子菜单=false;
temp.name=名称;
}
}
}
这适用于前3个菜单项,当引号中的菜单项名称有几个单词长时,我的问题就出现了。我知道这是因为使用提取操作符只提取第一个空格。为了丢失引号,我还必须使用stringsubstr方法
我不确定是否有更好的方法来提取数据并忽略引号,而且我无法更改数据存储的格式
提取这些信息的最佳方式是什么 多亏了@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;
}
}
}
if(fin.is_open())
{
getline(fin,this->title);
整数项;
fin>>数量项目;
对于(int i=0;i>tempshit;
if(tempshit==“菜单”)
{
字符串名,文件路径,temp2;
getline(fin,temp2,“”);
getline(fin,name,“”);
getline(fin,temp2,“”);
getline(fin,filepath,“”);
temp.is_子菜单=真;
temp.name=名称;
temp.subnumpath=文件路径;
}
其他的
{
字符串名,temp2;
getline(fin,temp2,“”);
getline(fin,name,“”);
temp.is_子菜单=false;
temp.name=名称;
}
}
}
不是直接的解决方案,但是如果您对文件格式有控制,您应该考虑使用不同的分隔符,如选项卡。我无法控制文件格式。我必须使用此特定格式。在阅读命令菜单
或选项
后,您可能希望使用getline
获取行的其余部分,忽略空格。你甚至可以告诉getline
阅读到下一个引号。你可以使用getline
阅读整行,然后逐字符阅读。@BenVoigt我喜欢这个想法,但是有没有办法阅读到第二个引号?