SHARE
TWEET

Untitled

a guest Sep 22nd, 2019 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <map>
  3. #include <fstream>
  4. #include <utility>
  5.  
  6. using namespace std;
  7.  
  8. map<string,int> count(string file_name, string to_read)
  9. {
  10.     fstream file;
  11.     file.open(file_name, fstream::in);
  12.  
  13.     if(!file.is_open())
  14.         throw -1;
  15.  
  16.     file << to_read;
  17.     map<string,int> result;
  18.     string current;
  19.  
  20.  
  21.     while(file >> current)
  22.     {
  23.         int occurrences = 0;
  24.         string next;
  25.         while(file >> next)
  26.             if(current == next)
  27.                 ++occurrences;
  28.  
  29.         pair<string,int> to_insert;
  30.         to_insert.first = current;
  31.         to_insert.second = occurrences;
  32.         result.insert(to_insert);
  33.     }
  34.  
  35.     file.close();
  36.     return result;
  37.  
  38. }
  39.  
  40. int main()
  41. {
  42.     string file_name = "esercizio.txt";
  43.     string sentence = "Chi va piano piano va sano e va lontano lontano";
  44.     map<string,int> result = count(file_name, sentence);
  45.  
  46.  
  47.     for(auto it = result.begin(); it != result.end(); ++it)
  48.         cout << it->first << " -> " << it->second << " occurrences" << endl;
  49.  
  50.     return 0;
  51. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top