[英]Getline and EOF
我正在嘗試讀取文件。 文件內容在句子中的單詞之間有一個換行符,在句子之間有兩個換行符。 我只能讀一句話。 我試圖將EOF作為getline中的定界符,但似乎不起作用。 有人對如何解決這個問題有任何建議嗎?
文件內容為:
縣
盛大
陪審團
周五說,對亞特蘭大最近的初診
選舉產生了。 沒有證據 '' 。 那個
發生違規行為。 。 陪審團進一步表示
市執行委員會的期末報告但是打印出來的是:
縣
大陪審團周五表示,對亞特蘭大
最近的初選產生了。 沒有證據 '' 。 任何違規行為發生了。 。
string line;
string a, b;
ifstream infile("myFile");
while (getline(infile, line))
{
istringstream iss(line);
if (!(iss >> a >> b)) { break; } // error
cout << a << b << endl;
}
#include <iostream>
#include <vector>
#include <boost/tokenizer.hpp>
using namespace std;
typedef boost::tokenizer<boost::char_separator<char>,
std::istreambuf_iterator<char> >
tokenizer;
void printPhrase(const vector<string>& _phrase) {
if (!_phrase.empty()) {
vector<string>::const_iterator it = _phrase.begin();
cout << "Phrase: \"" << *it;
for(++it; it != _phrase.end(); ++it)
cout << "\", \"" << *it;
cout << "\"" << endl;
} else
cout << "Empty phrase" << endl;
}
int main() {
boost::char_separator<char> sep("", "\n", boost::drop_empty_tokens);
istreambuf_iterator<char> citer(cin);
istreambuf_iterator<char> eof;
tokenizer tokens(citer, eof, sep);
int eolcount = 0;
vector<string> phrase;
for (tokenizer::iterator it = tokens.begin(); it != tokens.end(); ++it) {
if (*it == "\n") {
eolcount ++;
if (eolcount > 1 && eolcount % 2 == 0) { // phrase end
printPhrase(phrase);
phrase.clear();
}
} else {
eolcount = 0;
phrase.push_back(*it);
}
}
if (!phrase.empty())
printPhrase(phrase);
return 0;
}
基本思想是將換行符保留在輸出中,對它們進行計數,如果到目前為止已收集到2、4,..偶數個連續換行符,則會打印出單詞。 非換行標記會破壞序列,並且此標記會添加到累加器中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.