-5

hello im trying to compare 2 text file and find if the string in the first file exist or not.

first text file:

11111 22222 33333 44444 55555 77777

second text file:

11111 22222 44444 AAAAA BBBBB 55555 66666 CCCCC

The output should be:

11111 Match found
22222 Match found
33333 No Match
44444 Match found
55555 Match found
77777 No Match

what i got is:

11111 Match found
22222 Match found
33333 No Match
44444 No Match
55555 No Match
77777 No Match

This is my code:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main(){
    ifstream File1;
    ifstream File2;
    ofstream File3;
    string line,line2;


File1.open("A.txt");
File2.open("B.txt");
File3.open("OutputA.txt");
if(File1.fail()){ cerr<<"Error opening file !!"<<endl;exit(1);}
if(File2.fail()){ cerr<<"Error opening file !!"<<endl;exit(1);}



while(!File1.eof()){ //read file until you reach the end
        getline(File1,line);
    getline(File2,line2);
     if(line==line2){
    File3<<line<<"   Match"<<endl;
     }
     else{
         File3<<line<<"   Not Match"<<endl;
    }
        }


File1.close();
File2.close();
File3.close();

return 0;
}
  • 1
    https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong –  Feb 20 '18 at 02:20
  • Your `if(line == line2)` only go through line by line from txt file but doesn't compare the string exist on the previous or next line. – JaxLee Feb 20 '18 at 02:30
  • Besides what Neil just pointed out, it looks like you'll want to consume both files then compare each line of the first file to every line of the second file looking for a match. – Justin Randall Feb 20 '18 at 02:30
  • A `std::set` is a good choice for storing the strings of file B. Then you can easily use its `count` method for checking existence of each string in A. – Cheers and hth. - Alf Feb 20 '18 at 02:31
  • Recommend you move reading b.txt to an inner loop. Else you have a logic error since you firgot to always read from the beginning from the file for marches... not from your last position. – Stephen Quan Feb 20 '18 at 02:32

1 Answers1

1

Make your file reading logic look something like this. You want to compare the entire contents of File2 up until you find a match from your current position in File1. This should do what you want.

std::string lineA;
std::string lineB;
while (std::getline(File1, lineA))
{
    bool found(false);
    // read File2 until match is found
    while (std::getline(File2, lineB))
    {
        if (lineA == lineB)
        {
            found = true;
            File3 << lineA << " Match found" << std::endl;
            break;
        }
    }
    if (!found)
    {
        File3 << lineA << " No Match" << std::endl;
    }
    // clear the state of File2 stream
    File2.clear();
    File2.seekg(0, ios::beg);
}
Justin Randall
  • 1,981
  • 2
  • 12
  • 18