gpt4 book ai didi

c++ - 使用堆栈检查正确的HTML标记的C++程序

转载 作者:行者123 更新时间:2023-12-03 07:26:01 25 4
gpt4 key购买 nike

我一直在尝试在我的数据结构教科书上使用示例代码。
它是一个使用堆栈检查C++中括号平衡的程序,但未按预期工作。我以某种方式遇到HTML标记匹配算法的问题。

#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标签列表后,控制台没有响应。
我想寻求帮助来改进这些代码。任何想法表示赞赏。

最佳答案

It runs without a compilation error, but for some reason the console does not respond after I throw a list of HTML tags.



它为我运行,并且显示了我尝试过的几个测试用例的正确输出。
我使用的输入是:
1
<html>
<head></head>
<body></body>
</html>

您是否有机会忘记在实际输入html标记之前输入int?
如果没有,您可以显示您的输入吗?

关于c++ - 使用堆栈检查正确的HTML标记的C++程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46397841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com