[英]Problematic white spaces while reading a file
我正在使用以下代碼解析html文檔:
ifstream myfile("file.html");
string line;
int m_lines;
char c;
while(getline(myfile,line)) {
if(line.empty()) {
m_lines++;
continue;
}
istringstream iss(line);
while(iss.good()) {
c = iss.get();
//my code here (not important for this question)
cout << c;
}
m_lines++;
}
輸入文件(file.html)如下所示:
<p>Lorem ipsum <strong>haha</strong> gfadf.</p>
<img src="image.jpg" alt="alt" />
輸出:
<p>Lorem ipsum golo gama<strong>haha</strong> gfadf.</p> <img src="image.jpg" alt="alt" />
^
^
^
如果輸入文件中有換行,它將打印一個空格字符。 如何跳過或刪除此字符?
您的流中沒有換行符,調用getline
時它將提取直到換行符的字符。 iss.get()
返回文件結尾,因為沒有更多的字符可提取。 您可以使用以下代碼進行檢查:
while(iss.good()) {
c = iss.get();
if (c == std::char_traits<char>::eof())
{
cout << "end of file!";
}
else
{
cout << c;
}
}
您可以簡單地檢查字符串中的最后一個字符是否為空格字符(例如\\f\\n\\r\\t\\v
..)並將其刪除。 例:
while (line.back() == '\s')
{
line.erase(line.end());
}
如果您不使用c ++ 11(c ++ 11中添加了.back()
)
while (line[line.size()-1] == '\s')
{
line.erase(line.end());
}
您可以在istringstream iss(line);
之前添加它istringstream iss(line);
並刪除所有尾隨空格字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.