C++ program to print unique words in a file

A file is a memory location that stores word streams. In a file, there are various words. In this program, we will find all unique words from the file and print them.

A unique word means the number of occurrences of the word is one in the file.

For example,

Tutorials point is best for programming tutorials.

Here, the word tutorial occurs more than once, hence it is not unique. Rest all words are unique.


To check for unique words in the given file.
Using iterator with two variables : data and occurence.
Input : File
Step 1 : Read each line from the file and follow step 2
Step 2 : check for the occurence of the word in the data structure using interator.data.
   Step 2.1 : if data matches increase the occurrence by one corresponding to the data.
   Step 2.2 : if data does not match add new value and set its occurence to one.
Step 3: Iterate over the date structure. And check for occurence value of each value.
   Step 3.1 : If the occerence is equals to 1 then prints the data corresponding it else do nothing.


#include <bits/stdc++.h>
using namespace std;
int main(){
   char filename[] = "test.txt";
   ofstream fs("test.txt", ios::trunc);
   fs << "tutorials point is best for programming tutorials";
   fstream fs("test.txt");
   map<string, int> mp;
   string word;
   while (fs >> word){
      if (!mp.count(word))
         mp.insert(make_pair(word, 1));
   for (map<string, int> :: iterator p = mp.begin();
   p != mp.end(); p++){
      if (p->second == 1)
         cout << p->first << endl;
   return 0;



Updated on: 19-Sep-2019


Kickstart Your Career

Get certified by completing the course

Get Started