我有两个文本文件,在不同的行上包含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 opened\n");
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 opened\n");
getchar();
exit(EXIT_FAILURE); // Checks the file has been opened
}
printf("I have opened the QA and AR file\n");
//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;
}
我知道我的步骤是什么,我不确定如何最好地实现它们,最好使用两个阵列?同样逐行阅读的最简单方法是什么?我编码任何东西已经有几年了,所以任何建议都会很棒。
答案 0 :(得分:1)
如果有效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;
}
}