我試圖打印包含在字符串中的所有html標籤。在這裏,代碼的邏輯似乎有錯誤,我一直在得到一個永無止境的循環。從字符串中打印出HTML標籤
string fileLine;
string strToPush;
fileLine ="<html> sdad </b>as"; // My string that I want to find tags from
cout << fileLine << '\n';
while(!fileLine.length()==0)
{
if(fileLine.at(0)=='<')
{
strToPush = "";
while(!fileLine.at(0)=='>')
{
strToPush = strToPush + fileLine.at(0);
fileLine.erase (0);
}
cout << endl << "HTML Tag detected: " << strToPush <<endl;
}
else
{
fileLine.erase (0);
}
}
您應該使用HTML或XML解析器,這樣你就不會浪費時間調試功能。 – 2015-03-13 17:09:55
我懷疑你的問題在於涉及'!'和'=='的比較。 例如,你的while循環......你真的打算'!fileline.length()== 0'嗎?或者,也許你真的想'fileline.length()!= 0'甚至'!(fileline.length()== 0)'。 正如你寫的那樣,當長度爲零時,'!fileline.length()'將被評估爲真,當長度不爲零時則被評爲假。比較真正的== 0將是錯誤的,假== 0將是真實的......混亂,不是嗎? 如果您的意思是檢查長度不爲零,則使用不等於運算符:'!=' – 2015-03-13 17:11:19
如果您只想搜索模式'<[^<>] *>',則正則表達式可以提供幫助。但是,這也會報告評論內的事件並且不會驗證任何內容。如果您需要更多功能,請使用上面建議的專用庫。 – 5gon12eder 2015-03-13 17:15:01