c++语言比较两个文件内容并输出相同的内容
时间: 2023-08-12 17:04:08 浏览: 123
可以使用C++的STL库中的set容器来比较两个文件的内容,并输出相同的内容。具体步骤如下:
1. 打开两个文件,并将它们的内容分别读入两个字符串中。
2. 将第一个字符串中的每个单词插入到一个set容器中。
3. 遍历第二个字符串中的每个单词,如果该单词存在于set容器中,则说明这两个文件有相同的内容,将该单词输出。
下面是示例代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <set>
using namespace std;
int main() {
ifstream file1("file1.txt");
ifstream file2("file2.txt");
string str1((istreambuf_iterator<char>(file1)), istreambuf_iterator<char>());
string str2((istreambuf_iterator<char>(file2)), istreambuf_iterator<char>());
set<string> wordSet;
string word = "";
for (int i = 0; i < str1.length(); i++) {
if (str1[i] != ' ' && str1[i] != '\n') {
word += str1[i];
} else {
wordSet.insert(word);
word = "";
}
}
wordSet.insert(word);
word = "";
for (int i = 0; i < str2.length(); i++) {
if (str2[i] != ' ' && str2[i] != '\n') {
word += str2[i];
} else {
if (wordSet.find(word) != wordSet.end()) {
cout << word << " ";
}
word = "";
}
}
if (wordSet.find(word) != wordSet.end()) {
cout << word << " ";
}
file1.close();
file2.close();
return 0;
}
```
其中,file1.txt和file2.txt是需要比较的两个文件。在上面的示例代码中,我们将文件内容读入到两个字符串中,然后遍历第一个字符串,将每个单词插入到set容器中。接着,我们遍历第二个字符串,如果该单词存在于set容器中,则说明这两个文件有相同的内容,将该单词输出即可。