How to insert c++ find into a while loop?

时间:2016-04-04 18:21:04

标签: c++ while-loop find

I use a while loop with the find function in c++ but I need to use the position found like the condition of the while loop but Visual Studio shome me

An unhandled exception of type 'System.Runtime.InteropServices.SEHException' occured in Test.exe

Additional information: External component has thrown an exception.

I use this code:

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;
}

what is the problem?

1 个答案:

答案 0 :(得分:0)

感谢PaulMcKenzie的帮助,我解决了我的问题。我修改了我的代码以插入boolean变量并控制pos1pos2是否找到string<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;
    }

}