栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Essential C++ 练习3.1

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Essential C++ 练习3.1

要求:

写一个读取文本文件的程序,将文件中的每个单字存入map。
map的key便是刚才所说的单字,map的value则是该单字在文本文件中出现的次数。
再定义一份由“排除字眼”组成的set,其中包含诸如a、an、or、and和but之类的单字。
将某单字放入map之前,先确定该单字并不在“排除字集”中。
一旦文本文件读取完毕,请显示一份单字清单,并显示各单字的出现次数。
你甚至可以再加扩展,在显示单字之前,允许用户查询某个单字是否出现于文本文件中。

#include
#include
#include
#include

using namespace std;

void initialize_exclusion_set(set& exs);
void process_file(map& word_cout, const set& exclude_set, ifstream& ifile);
void usr_query(const map& word_map);
void display_word_count(const map& word_map, ofstream& os);

int main()
{
	ifstream ifile("E:\VSCODE\练习3.1\源文件.txt");
	ofstream ofile("E:\VSCODE\练习3.1\排序文件.txt");
	if (!ifile||!ofile)
	{
		cerr << "Unable to open file -- bailing out" << endl;
		return EXIT_FAILURE;
	}
	set exclude_set;
	initialize_exclusion_set(exclude_set);

	map word_count;
	process_file(word_count, exclude_set, ifile);
	usr_query(word_count);
	display_word_count(word_count, ofile);

	system("pause");
	return EXIT_SUCCESS;
}

void initialize_exclusion_set(set& exs)
{
	static string _excluded_words[63] = {
		"the","and","but","that","then","are","been",
		"can","a","could","did","for","of","had","is",
		"have","him","it","his","her","its","were","which",
		"when","where","with","would","b","c","d","e","f","g",
		"h","i","j","k","l","m","n","o","p","q","r","s","t","u",
		"v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","0"
	};

	exs.insert(_excluded_words, _excluded_words + 63);
}
void process_file(map& word_cout, const set& exclude_set, ifstream& ifile)
{
	string word;
	while (ifile>>word)
	{
		if (exclude_set.count(word))
		{
			continue;
		}
		word_cout[word]++;
	}
}
void usr_query(const map& word_map)
{
	string search_word;
	cout << "Please enter a word to search: q to quit ";
	cin >> search_word;
	while (search_word.size()&&search_word!="q")
	{
		map::const_iterator it;
		if ((it=word_map.find(search_word))!=word_map.end())
		{
			cout << "Found! " << it->first << " occurs " << it->second << " times." << endl;
		}
		else
		{
			cout << search_word << " was not found in text!" << endl;
		}
		cout << "Another search? (q to quit) ";
		cin >> search_word;
	}
}
void display_word_count(const map& word_map, ofstream& os)
{
	map::const_iterator iter = word_map.begin(), end_it = word_map.end();
	while (iter!=end_it)
	{
		os << iter->first << " ( " << iter->second << " ) " << endl;
		++iter;
	}
	os << endl;
}

源文件:

字数统计后文件:

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/768531.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号