Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ พิมพ์คำเฉพาะในไฟล์


ไฟล์คือตำแหน่งหน่วยความจำที่เก็บกระแสคำ ในไฟล์มีคำต่างๆ ในโปรแกรมนี้ เราจะค้นหาคำที่ไม่ซ้ำทั้งหมดจากไฟล์และพิมพ์ออกมา

มีเอกลักษณ์ word หมายถึง จำนวนครั้งของคำนั้นอยู่ในไฟล์หนึ่งคำ

ตัวอย่างเช่น

Tutorials point is best for programming tutorials.

ที่นี่ การสอนคำศัพท์เกิดขึ้นมากกว่าหนึ่งครั้ง ดังนั้นจึงไม่ซ้ำกัน พักทุกคำไม่ซ้ำกัน

อัลกอริทึม

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";
   fs.close();
   fstream fs("test.txt");
   map<string, int> mp;
   string word;
   while (fs >> word){
      if (!mp.count(word))
         mp.insert(make_pair(word, 1));
      else
         mp[word]++;
   }
   fs.close();
   for (map<string, int> :: iterator p = mp.begin();
   p != mp.end(); p++){
      if (p->second == 1)
         cout << p->first << endl;
   }
   return 0;
}

ผลลัพธ์

best
for
is
point
Programming