2013-03-18 194 views
0
#include <iostream> 
#include <fstream> 
#include <cstdlib> 
#include <string> 
#include <map> 

using namespace std; 

int main() 
{ 
    ifstream fin; 
    fin.open("myTextFile.txt"); 
    if (fin.fail()){ 
     cout << "Could not open input file."; 
     exit(1); 
    } 

    string next; 
    map <string, int> words; 
    while (fin >> next){ 
     words[next]++; 
    } 
    cout << "\n\n" << "Number of words: " << words[next] << endl; 

    fin.close(); 
    fin.open("myTextFile.txt"); 
    while (fin >> next){ 
     cout << next << ": " << words[next] << endl; 
    } 

    fin.close(); 
    return 0; 
} 

我的主要問題是,當一個單詞出現不止一次時,它也會多出現一次。即如果文本以「hello hello」開頭,那麼cout產生: 「hello:2」'n'「hello:2」使用映射計算每個單詞在文件中出現的次數。 (C++)

另外,我想不必關閉,然後重新打開文件第二次是真實的。它看起來仍然在最後while循環的文件末尾。

+5

你的單詞數量只會打印最後一個單詞的數量。另外,遍歷地圖,不要再次讀取文件(假設你改了名字,忘記改變另一個,根據你說的重新打開來判斷)。 – chris 2013-03-18 15:22:39

回答

2

您需要迭代通過地圖,而不是第二次打開文件。

看看提供的代碼示例here

編輯:下面一個代碼示例,迭代低谷地圖

// map::begin/end 
#include <iostream> 
#include <map> 

int main() 
{ 
    std::map<char,int> mymap; 
    std::map<char,int>::iterator it; 

    mymap['b'] = 100; 
    mymap['a'] = 200; 
    mymap['c'] = 300; 

    // show content: 
    for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it) 
    std::cout << it->first << " => " << it->second << '\n'; 

    return 0; 
} 

這裏是輸出:

a => 200 
b => 100 
c => 300 
+0

你也可以在你的答案中提供正確的代碼嗎? – Pubby 2013-03-18 15:24:40

2

您不必再打開文件:

for (auto i = words.begin(); i != words.end(); i++) 
{ 
    cout << i->first << " : " << i->second << endl; 
} 

或更簡單:

for (const auto &i : words) 
{ 
    cout << i.first << " : " << i.second << endl; 
} 
+1

如果你使用的是C++ 11,那麼也可以使用基於範圍的! – Pubby 2013-03-18 15:30:27

0

你需要你設置它,那麼你就不需要再次打開該文件後,迭代在地圖上,這是簡單的例子:

int main() 
{ 
    std::map<std::string, int> m1 ; 

    m1["hello"] = 2 ; 
    m1["world"] = 4 ; 

    for(const auto &entry : m1) 
    { 
    std::cout << entry.first << " : " << entry.second << std::endl ; 
    } 
} 

預期輸出是:

hello : 2 
world : 4 
相關問題