数据结构小作业-串模式匹配 | C++文件流读写

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
const int maxn = 1e4;
int nex[maxn];
string a, b;
int lena, lenb;
vector<int> ans;

void NewFile()//C++文件流创建文件
{
	cout << "请输入要创建的文件名称:" << endl;
	string name; cin >> name; getchar(); name += ".txt";
	cout << "请输入文本(以Ctrl+z结束)" << endl;
	ofstream outfile(name.c_str());
	string buf;
	while (getline(cin, buf))
	{
		outfile << buf << endl;
	}
	cout << "文件创建成功" << endl;
	outfile.close();
}

void getnex()//next数组处理
{
	int j = 0, k = -1;
	nex[0] = -1;
	while (j < lenb)
	{
		if (k == -1 || b[j] == b[k])
			nex[++j] = ++k;
		else k = nex[k];
	}
}

int kmpcount()//kmp算法
{
	getnex();
	ans.clear();
	int i = 0, j = 0, res = 0;
	while (i < lena)
	{
		while (b[j] != a[i] && j > 0)
			j = nex[j];
		if (a[i] == b[j]) j++;
		if (j == lenb) res++, ans.push_back(i - lenb + 1), j = nex[j];
		i++;
	}
	return res;
}

void count()//功能2
{
	cout << "请输入要查询的文件名称:" << endl;
	string name; cin >> name; getchar(); name += ".txt";
	ifstream infile(name.c_str());
	cout << "请输入您要计数的单词" << endl;
	cin >> b; lenb = b.length();
	int res = 0;
	while (getline(infile, a))
	{
		lena = a.length();
		res += kmpcount();
	}
	cout << "匹配到的个数为:" << res << endl;
}

void search()//功能3
{
	cout << "请输入要查询的文件名称:" << endl;
	string name; cin >> name; getchar(); name += ".txt";

	ifstream infile(name.c_str());
	cout << "请输入您要计数的单词" << endl;
	cin >> b; lenb = b.length();
	int lines = 0, flag = 0;
	while (getline(infile, a))
	{
		lines++;
		lena = a.length();
		int res = kmpcount();
		if (res)
		{
			flag = 1;
			printf("第%d行内容为:%s共匹配到%d处, 起始位置是: ", lines, a.c_str(), res);
			for (int i = 0; i < ans.size(); i++)
				printf("%d%c", ans[i] + 1, i == ans.size() - 1 ? '\n' : ' ');
		}
	}
	if (!flag) cout << "未匹配到相关单词" << endl;
}


bool menu() //菜单显示
{
	cout << "***文本匹配系统***" << endl;
	cout << "1、建立文件" << endl;
	cout << "2、单词计数" << endl;
	cout << "3、单词定位" << endl;
	cout << "4、退出程序" << endl;
	cout << "请输入操作序号" << endl;
	cin.clear();
	int ope; cin >> ope;
	switch (ope)
	{
	case 1:
		NewFile();
		break;
	case 2:
		count();
		break;
	case 3:
		search();
		break;
	case 4:
		return false;
	default:
		return false;
	}
	system("pause");
	system("cls");
	return true;
}

int main()
{
	while (menu());
}