2013-01-24 36 views
1

我目前正在C++中的一個小項目,目前有點困惑。我需要從if()中的ifstream文件中讀取一定數量的單詞。現在的問題是它一直忽略空間。我需要計算文件中空格的數量來計算單詞的數量。反正有()不要忽略空白嗎?閱讀整個行包括從fstream的空間

ifstream in("input.txt");  
ofstream out("output.txt"); 

while(in.is_open() && in.good() && out.is_open()) 
{ 
    in >> temp; 
    cout << tokencount(temp) << endl; 
} 
+9

[std :: getline](http://en.cppreference.com/w/cpp/string/basic_string/getline) – jrok

+0

你能在你的問題中包含代碼片段嗎?當問題更清楚時,答案可以更具體。 – Mogsdad

+0

您可以配置C++流是否應該忽略空白,如果我沒有記錯的話,它被稱爲「skipws」。 –

回答

3

要計算的空格數在一個文件中:

std::ifstream inFile("input.txt"); 
std::istreambuf_iterator<char> it (inFile), end; 
int numSpaces = std::count(it, end, ' '); 

要計算的空白字符在文件數:代替計數

std::ifstream inFile("input.txt"); 
std::istreambuf_iterator<char> it (inFile), end; 
int numWS = std::count_if(it, end, (int(*)(int))std::isspace); 

作爲替代方案,空格,你可以計數單詞

std::ifstream inFile("foo.txt); 
std::istream_iterator<std::string> it(inFile), end; 
int numWords = std::distance(it, end); 
+0

+1爲istreambuf_iterator 絕招。我想知道是否有沿着這些行可以讓你用一個迭代器來完成整個文件:) –

2

以下是我會做:

std::ifstream fs("input.txt"); 
std::string line; 
while (std::getline(fs, line)) { 
    int numSpaces = std::count(line.begin(), line.end(), ' '); 
} 

一般情況下,如果我有一個文件的每一行做一些事情,我發現的std ::函數getline是最挑剔的方式做到這一點。如果我需要從那裏開發流操作符,那麼我會最終將stringstream從這一行中刪除。這遠不是最有效的做事方式,但我通常更關心如何正確做事,並繼續爲這類事情而生活。

1

可以使用countistreambuf_iterator

ifstream fs("input.txt"); 

int num_spaces = count(istreambuf_iterator<unsigned char>(fs), 
         istreambuf_iterator<unsigned char>(), 
         ' '); 

編輯

本來我的回答使用istream_iterator,然而由於@Robᵩ指出,這是行不通的。

istream_iterator將遍歷一個流,但假定空白格式並跳過它。我上面的例子,但使用istream_iterator返回結果爲零,因爲迭代器跳過空白,然後我要求它計算剩下的空格。

istreambuf_iterator然而,一次只需要一個原始字符,不會跳過。

有關更多信息,請參閱istreambuf_iterator vs istream_iterator

+1

[代碼](http://ideone.com/hc2vrS)不會做你認爲的事情確實。事實上,它總是返回零。 –

+0

感謝您的反饋,@Robᵩ –