簡體   English   中英

比較 C++ 中的 2 個文本文件

[英]comparing 2 text file in C++

你好,我正在嘗試比較 2 個文本文件並查找第一個文件中的字符串是否存在。

第一個文本文件:

11111 22222 33333 44444 55555 77777

第二個文本文件:

11111 22222 44444 AAAAA BBBBB 55555 66666 中國交建

輸出應該是:

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

我得到的是:

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

這是我的代碼:

#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;
}

使您的文件讀取邏輯看起來像這樣。 您想比較 File2 的全部內容,直到從 File1 中的當前位置找到匹配項。 這應該做你想做的。

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM