2016-04-04 5 views
-2

私はC++find機能付きwhileループを使用しますが、私はポジションを使用する必要があるが、whileループの条件のように見つかりましたが、Visual StudioのwhileループにC++のfindを挿入するには?

タイプ「システムの未処理の例外が私をSHOME .Runtime.InteropServices.SEHException 'がTest.exeで発生しました

追加情報:外部コンポーネントから例外がスローされました。

私はこのコードを使用します。

int dim=myString.length(); 
while (dim>=0) 
{ 
    size_t pos1 = myString.find("<article"); 
    size_t pos2 = myString.find("</article>"); 
    std::string buf = myString.substr(pos1, pos2 - pos1 + 10); 
    myString = myString.substr(pos2 + 10); 
    ofstream myfile("body.txt"); 
    if (myfile.is_open()) 
    { 
     myfile << myString; 
     myfile.close(); 
    } 
    else cout << "Unable to open file"; 

    //cout << myString << endl; 
    ptree xmlTree; 
    string title[1000]; 
    int j = 0; 
    try 
    { 
     stringstream ss; 
     ss << buf; 
     read_xml(ss, xmlTree); 
     const ptree & formats = xmlTree.get_child("article", empty_ptree()); 
     BOOST_FOREACH(const ptree::value_type & f, formats) 
     { 
      string at = f.first + ATTR_SET; 
      const ptree & attributes = f.second.get_child("<xmlattr>", empty_ptree()); 
      //cout << "Extracting attributes from " << at << ":" << endl; 
      BOOST_FOREACH(const ptree::value_type &v, attributes) 
      { 
       string first = v.first.data(); 
       //cout << "First: " << v.first.data() << " Second: " << v.second.data() << endl; 
       if (first == "title") 
       { 
        title[j] = v.second.data(); 
        j++; 
       } 
      } 
     } 
     for (int a = 0; a < j; a++) 
     { 
      cout << title[a] << endl; 
     } 

    } 
    catch (xml_parser_error &e) { 
     cout << "Failed to read config xml " << e.what() << endl; 
    } 
    catch (...) { 
     cout << "Failed to read config xml with unknown error" << endl; 
    } 
    dim = dim - pos2; 
} 

問題が何でありますか?

+0

ほとんどの部分文字列のいずれかが見つかりませんでした、myString'は '場合はその結果を対応する'のstd ::文字列:: npos'、すべての結果のサブ –

+0

であります空の場合、コードは失敗します。 – PaulMcKenzie

+0

@AntonSavinこの問題を解決するにはどうすればよいですか? – Shaila

答えて

0

私はPaulMcKenzieの助けを借りて私の問題を解決します。 boolean変数を挿入し、pos1pos2stringのいずれかが「<article」と「</article>」と一致するかどうかを制御するコードを変更します。

これはコードです:

int dim = myString.length(); 
    boolean in=true; 

while (in==true) 
{ 
    size_t pos1 = myString.find("<article"); 
    size_t pos2 = myString.find("</article>"); 
    if (pos1 != std::string::npos && pos2 != std::string::npos) 
    { 
     std::string buf = myString.substr(pos1, pos2 - pos1 + 10); 
     myString = myString.substr(pos2 + 10); 

     ofstream myfile("body.txt"); 
     if (myfile.is_open()) 
     { 
      myfile << myString; 
      myfile.close(); 
     } 
     else cout << "Unable to open file"; 
     //some code 
     dim = dim - myString.length(); 
      in = true; 
    } 
    else 
    { 
      in = false; 
      cout << " - - - - - - - - - - " << endl; 
    } 

}