Skip to content
Related Articles

Related Articles

Improve Article

C++ program to print unique words in a file

  • Last Updated : 28 Jun, 2021

Write a function that takes a file name as argument and prints all unique words in it.

We strongly recommend you to minimize your browser and try this yourself first

The idea is to use map in STL to keep track of words already occurred.




// C++ program to print unique words in a string
#include <bits/stdc++.h>
using namespace std;
  
// Prints unique words in a file
void printUniquedWords(char filename[])
{
    // Open a file stream
    fstream fs(filename);
  
    // Create a map to store count of all words
    map<string, int> mp;
  
    // Keep reading words while there are words to read
    string word;
    while (fs >> word)
    {
        // If this is first occurrence of word
        if (!mp.count(word))
            mp.insert(make_pair(word, 1));
        else
            mp[word]++;
    }
  
    fs.close();
  
    // Traverse map and print all words whose count
    //is 1
    for (map<string, int> :: iterator p = mp.begin();
         p != mp.end(); p++)
    {
        if (p->second == 1)
            cout << p->first << endl;
    }
}
  
// Driver program
int main()
{
    // Create a file for testing and write something in it
    char filename[] = "test.txt";
    ofstream fs(filename, ios::trunc);
    fs << "geeks for geeks quiz code geeks practice for qa";
    fs.close();
  
    printUniquedWords(filename);
    return 0;
}

Output:

code
practice
qa
quiz

Thanks to Utkarsh for suggesting above code.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :