2017-09-25 17 views
0

我一直在尝试遵循我的数据结构教科书上的示例代码。 这是一个程序来检查C++中使用堆栈的括号的平衡,但它不像预期的那样工作。不知何故,我遇到了HTML标签匹配算法的问题。用于检查正确的HTML标记使用堆栈的C++程序

#include <iostream> 
#include <stack> 
#include <vector> 
#include <string> 
using namespace std; 

vector<string> getHtmlTags() {          //receives a string of html tags and divide them by "<, >" 
    vector<string> tags;           //vector of html tags 
    while (cin) {             //reads the whole input 
     string line; 
     getline (cin,line); 
     int pos = 0;            //current scanning position 
     int ts = line.find("<",pos);        //scans from the current scanning position 
     while (ts!=string::npos) {         //repeat until end of string 
      int te = line.find(">", ts+1);       //scans for the end of a tag (<) 
      tags.push_back(line.substr(ts,te-ts+1));    //save tag to the vector 
      pos = te + 1;           //repositioning 
      ts = line.find("<",pos); 
     } 
    } 
    return tags;             //return vector of tags 
} 


bool isHtmlMatched(const vector<string>& tags) {     //checks if the html tags are correctly matched 
    stack<string> S;           //implememted stack from above for opening tags 
    typedef vector<string>::const_iterator Iter;     //iterate through vector 

    for (Iter p = tags.begin(); p != tags.end(); ++p) {    
     if (p->at(1) != '/')          //is it the opening tag? 
      S.push(*p);            //push to the stack 
     else{ 
      if (S.empty()) return false;       //there is nothing to match 
      string open = S.top().substr(1);      //opening tag excluding '<' 
      string close = p->substr(2);       //closing tag excluding '>' 
      if (open.compare(close) != 0) return false;    //exception for fail to match 
      else S.pop();           //pop matched element 

     } 
    } 
    if (S.empty()) return true;          //everything has matched correctly - Correct 
    else return false;            //some did not match correctly - Incorrect 
} 

int main() { 

    int rep;              //decides the number of trial 
    cin >> rep; 

    for (int i=1; i<=rep; i++) {         //loop up to the decided trial 
     if(isHtmlMatched(getHtmlTags())) 
      cout << "Correct" << endl; 
     else cout << "Incorrect" << endl; 
    } 
} 

它在运行时编译错误,但由于某些原因,我把HTML标签的列表后控制台没有响应。 我想请求帮助改进这些代码。任何想法都表示赞赏。

+0

您可以参考: https://github.com/nileshivam/Incomplete-HTML-code-completer – Nilesh

+0

@Nilesh请参阅PHP代码粗略的C++ HTML解析器?地狱不,我建议寻找已经存在于C++生态系统中的XML解析器。如果你只是试图将其作为练习,我会建议重新开始,对应用程序的目标有一个更清晰的概念。 – SeedyROM

回答

0

它运行时没有编译错误,但由于某种原因,控制台在我抛出HTML标记列表后没有响应。

它为我运行,它显示了我尝试过的几个测试用例的正确输出。 我使用的输入是:

1 
<html> 
<head></head> 
<body></body> 
</html> 

你有没有任何机会忘记输入实际进入的HTML标记前一个int? 如果不是,你能显示你的输入吗?