C ++程序在文件中打印唯一单词
文件是存储字流的存储位置。在一个文件中,有各种各样的单词。在此程序中,我们将从文件中找到所有唯一的单词并进行打印。
一个独特的词的意思的词出现的次数是一个在文件中。
例如,
nhooo.com 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 << "nhooo.com 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