我有两个文本文件,在单独的行上包含 7 位整数,我想要一个程序来比较一个文件中的整数和另一个文件。
使用的示例日期(大约 300+ 个单独的整数(
1867575
1867565
1867565
1867433
这是我到目前为止的代码,可以打开保存到桌面的两个文件。
#include <iostream> //I have no idea what these do...
#include <fstream> //Will be tidying this up once it all works
#include <cmath>
#include <cstdlib>
#include <stdlib.h>
#include <cstring>
#include <string>
#include <stdio.h>
using namespace std;
int main(){
ifstream arfile; // Declares the first text file Applicants records - AR
ifstream qvfile; // Declares the second text file Qualifaction records - QV
// Will be comparing intergers from AR list to Qv list
arfile.open("C:\Users\sagrh18\Desktop\ar.txt"); // Opens the AR file
if(!arfile.is_open()){
printf ("AR file hasn't openedn");
getchar();
exit(EXIT_FAILURE); // Checks the file has been opened
}else
{
qvfile.open("C:\Users\sagrh18\Desktop\qv.txt"); // Opens the Input file Qv for comparrsion.
if(!qvfile.is_open()){
printf ("QV file hasn't openedn");
getchar();
exit(EXIT_FAILURE); // Checks the file has been opened
}
printf("I have opened the QA and AR filen");
//Need a loop to comapare Ar lines to Qv lines
//If there is a match do nothing
//If there not a match then print off the number
}
printf ("Program has finsihed press Enter n");
getchar();
return 0;
}
我知道步骤是什么,我只是不确定如何最好地实现它们,使用两个数组是最好的吗?逐行阅读的最简单方法是什么?自从我编写任何东西以来已经有几年了,所以任何建议都会很棒。
给定有效的ifstream arfile
和ifstream qvfile
,您可以使用istream_iterator
来填充vectors
:
const vector<int> arvec { istream_iterator<int>(arfile), istream_iterator<int>() };
vector<int> qvvec { istream_iterator<int>(qvfile), istream_iterator<int>() };
读取两个文件的内容后,您现在需要比较文件,最快的方法是对qvvec
进行排序,然后使用binary_search
:
sort(begin(qvvec), end(qvvec));
for(const auto& i : arvec) {
if(!binary_search(cbegin(qvvec), cend(qvvec), i)) {
cout << i << endl;
}
}