0

次のコードでは、.yamlファイルを.yamlを使用して解析する際に何らかの問題が発生していますparser.GetNextDocument(doc);。多くの大まかなデバッグの結果、ここでの(主な)問題は、doc.size() == 0;何が間違っているのかが原因で、forループが実行されていないことであることがわかりました。

void
BookView::load()
{
  aBook.clear();

  QString fileName =
    QFileDialog::getOpenFileName(this, tr("Load Address Book"),
                 "", tr("Address Book (*.yaml);;All Files (*)"));
  if(fileName.isEmpty())
    {
      return;
    }
  else
    {
      try
    {
      std::ifstream fin(fileName.toStdString().c_str());
      YAML::Parser parser(fin);
      YAML::Node doc;
      std::map< std::string, std::string > entry;

      parser.GetNextDocument(doc);
      std::cout << doc.size();

      for( YAML::Iterator it = doc.begin(); it != doc.end(); it++  )
        {
          *it >> entry;
          aBook.push_back(entry);
        }

    }
      catch(YAML::ParserException &e)
    {
      std::cout << "YAML Exception caught: "
            << e.what()
            << std::endl;
    }
    }
  updateLayout( Navigating );
}

読み取られる.yamlファイルはyaml-cppを使用して生成されたため、正しく形成されたYAMLであると思いますが、念のため、ここにファイルを示します。

^@^@^@\230---
-
  address: ******************
  comment: None.
  email: andrew(dot)levenson(at)gmail(dot)com
  name: Andrew Levenson
  phone: **********^@

編集:リクエストにより、放出コード:

void
BookView::save()
{
  QString fileName =
    QFileDialog::getSaveFileName(this, tr("Save Address Book"), "",
                 tr("Address Book (*.yaml);;All Files (*)"));
  if (fileName.isEmpty())
    {
      return;
    }
  else
    {
      QFile file(fileName);
      if(!file.open(QIODevice::WriteOnly))
    {
      QMessageBox::information(this, tr("Unable to open file"),
                   file.errorString());
      return;
    }

      std::vector< std::map< std::string, std::string > >::iterator itr;
      std::map< std::string, std::string >::iterator mItr;
      YAML::Emitter yaml;

      yaml << YAML::BeginSeq;
      for( itr = aBook.begin(); itr < aBook.end(); itr++ )
    {
      yaml << YAML::BeginMap;
      for( mItr = (*itr).begin(); mItr != (*itr).end(); mItr++ )
        {
          yaml << YAML::Key << (*mItr).first << YAML::Value << (*mItr).second;
        }
      yaml << YAML::EndMap;
    }
      yaml << YAML::EndSeq;

      QDataStream out(&file);
      out.setVersion(QDataStream::Qt_4_5);
      out << yaml.c_str();
    }      
}
4

1 に答える 1

1

あなたの考えに沿って、問題は、あなたが書いているQDataStreamのに、プレーンを使って読んでいるということですstd::ifstream。どちらか一方を行う必要があります。

を使用する場合はQDataStream、それも読み込む必要があります。詳細についてはドキュメントを確認してください。ただし、YAML 文字列を取得するだけでよいようです。

QDataStream in(&file);
QString str;
in >> str;

そしてそれを yaml-cpp に渡します:

std::stringstream stream; // remember to include <sstream>
stream << str; // or str.toStdString() - I'm not sure about how QString works
YAML::Parser parser(stream);
// etc.

a のポイントは、std::stringstreamYAML を含む文字列を、YAML パーサーが読み取れるストリームに変換することです。

于 2011-02-01T23:22:19.053 に答える