从txt文件里两行找最长的相同单词
#include<iostream>
#include<string>
#include<cstring>
#include<fstream>
#include<vector>
using namespace std;
class selfstring
{
string datastr;
int length;
public:
selfstring(ifstream& is, int k)
{
getline(is, datastr);
length = k;
}
friend void search(selfstring& a, selfstring& b);
~selfstring(){}
};
void search(selfstring& a, selfstring& b)
{
string m[100];
string n[100];
for (int i = 0; i < a.length; i++)
{
m[i] = a.datastr.substr(0, a.datastr.find(" "));
a.datastr.erase(0, a.datastr.find(" ") + 1);
}
for (int i = 0; i < b.length; i++)
{
n[i] = b.datastr.substr(0, b.datastr.find(" "));
b.datastr.erase(0, b.datastr.find(" ") + 1);
}
string temp = " ";
int samelength = 0;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < b.length; j++)
{
if (m[i] == n[j] && m[i].length() > samelength)
{
temp = m[i];
samelength = m[i].length();
}
}
}
if (samelength != 0)
{
cout << "最长相同单词为:" << temp << "长度为:" << samelength << endl;
}
else cout << "无相同单词" << endl;
}
int main()
{
ifstream is1("C:\\Users\\25776/Desktop\\312.txt");
if(!is1)
{
cerr << "打开文件失败" << endl;
exit(EXIT_FAILURE);
}
ifstream is2("C:\\Users\\25776/Desktop\\311.txt");
if (!is2)
{
cerr << "打开文件失败" << endl;
exit(EXIT_FAILURE);
}
selfstring p(is1, 16);
selfstring q(is2, 16);
search(p, q);
}