如何在迭代器c++上调用toString

How to call toString on iterator c++

本文关键字:调用 toString c++ 迭代器      更新时间:2023-10-16

你好,我是编码新手,很抱歉我可能有任何误解,以及它看起来有多糟糕。我花了几个小时在这个问题上,但无法解决它。我有一个XMLItems向量和一个常量toString方法。当我尝试用迭代器调用toString时,它什么也不输出。

string XMLParser::toStringInput() const
{
string inputret = "";
  for(std::vector<XMLItem>::const_iterator iter = theInput.begin(); iter != theInput.end(); ++iter)
  {
  inputret += (*iter).toString();
  }
return inputret;
}

这不会返回任何结果。我用错迭代程序了吗?创建矢量时,字符串是否保存错误?这是XMLItem类中的toString

string XMLItem::toString() const
{
cout << this->theItem; //the item is a private string
return this->theItem;
}

这是我创建向量的地方,以防万一。

void XMLParser::readXML(Scanner& inStream)
{
string tmp = "";
string tag = "tag";
string data = "data";
XMLItem localxml = XMLItem();
while (inStream.hasNext())
{
string input = inStream.nextLine();
if(input.find("<") != std::string::npos)
{
  XMLItem localxml = XMLItem(tag, input);
}
else
{
  XMLItem localxml = XMLItem(data, input);
}
this->theInput.push_back(localxml);
}
}
XMLItem localxml = XMLItem();
while (inStream.hasNext()) {
  string input = inStream.nextLine();
  if(input.find("<") != std::string::npos) {
    XMLItem localxml = XMLItem(tag, input);
  } else {
    XMLItem localxml = XMLItem(data, input);
  }    
  this->theInput.push_back(localxml);
}

if的块和else的块中,都有一个名为localxml的新本地(对应于相应块(变量。它们对while循环之前定义的变量进行阴影处理,使其保持不变。所以你基本上可以运行

theInput.push_back(XMLItem());

在那个循环中。因此,稍后,当您尝试将向量的元素转换为字符串时,这些"空"元素会被转换,可能会导致一些空字符串被连接起来。

要解决此问题,请删除变量名称前面的类型,将变量声明更改为赋值:

localxml = XMLItem(tag, input);