我是 C++ 的初学者,并试图使检查按预期工作。但几乎所有测试都返回 true。在这种情况下,它只假设返回 true:
<red> Red blank <dim> I'm now dim and red. </dim> </red>
但这在现在也返回 true:
<red> Blah I'm red.<dim> Im dim now </red> </dim>
或这个 :
<red> blah <im dim now
所以我想知道我的代码中是否有一些我忽略的东西。
bool is_well_formed(ifstream& ifs, string& error_msg) {
string fname,line;
Token tok;
Lexer lexer;
tags.insert("blue");
tags.insert("red");
tags.insert("cyan");
tags.insert("white");
tags.insert("yellow");
tags.insert("magenta");
tags.insert("dim");
tags.insert("underline");
tags.insert("bold");
stack<string> tagstack;
while (getline(ifs, fname)) {
// tries to open the file whose name is in string fname
if (ifs.fail()) {
cerr << "ERROR: Failed to open file " << fname << endl;
ifs.clear();
} else {
while (getline(ifs, line)) {
lexer.set_input(line);
while (lexer.has_more_token()) {
tok = lexer.next_token();
string tmpTok = tok.value;
switch (tok.type) {
case TAG:
// If it has /, remove / from tmpTok
if (tok.value[0] == '/') {
// If it's a closing t
tmpTok = tmpTok.substr(1,tmpTok.length()-1);
}
if(tags.find(tmpTok) == tags.end()) {
// Check whether the encountered tag is valid
error_return("Tag " + tmpTok + " is invalid!");
return false;
} else {
// Valid Tag encountered
tagstack.push(tmpTok);
// Check if the tags are formed properly
if (tmpTok.find('/')) {
// Remove / from tmpTok
string closingTag = tmpTok;
string openingTag = tagstack.top();
tagstack.pop();
if(closingTag.compare(openingTag) != 0) {
error_return(closingTag+"doesn't match" +openingTag);
return false;
} //else
// return true; // if the file is well formed
}/**else{
tagstack.push(tmpTok);
}*/
}// else end
break;
case IDENT:
// cout << "IDENT: " << tok.value << endl;
break;
case ERRTOK:
error_return("Syntax error on this line\n");
return false;
//cout << "Syntax error on this line\n";
break;
case ENDTOK:
break;
}
}
}
}
}
return true; // if the file is well-formed
}