在文件中打印唯一字的C++程序

编写一个函数,将文件名作为参数,并打印其中所有唯一的单词。

null

我们强烈建议您尽量减少浏览器,并先自己尝试

这个想法是使用 STL中的地图 跟踪已经发生的单词。

// 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;
}


输出:

code
practice
qa
quiz

感谢Utkarsh提出上述代码。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享