简体   繁体   English

从新文件中的 output 文件中读取,并比较输出

[英]Read from file, output in a new file, and compare outputs

I need a little bit help with my code.我的代码需要一点帮助。 The first part of the code, was easy to create.代码的第一部分很容易创建。 Read from two textfiles -> Output in a new textfile.从两个文本文件中读取 -> Output 在一个新的文本文件中。 My next step is to compare the both outputs line by line.我的下一步是逐行比较这两个输出。

  • If the number is the same, the numbers stays.如果数字相同,则数字保持不变。
  • If the number is different to the number of textfile2, the number with be replaced.如果数字与 textfile2 的数字不同,则替换数字。

Example:例子:

Textfile1:
2221112221
1122221112
2222221111
1111111111

Textfile2:
2222221111
2211222212
1111111111
2221112222

Result that should happen on Textfile3:
(like I'm overlapping textfile2 on textfile1)

2222221111
2211222212
1111111111
2221112222

So I already researched for str.compare , but I'm not able to output the result as above stated.所以我已经研究了str.compare ,但我无法 output 如上所述的结果。 I don't know if this works with it.我不知道这是否适用。

if((line2.compare(0, line2.length(), line1)) == 0)
string line1, line2;
ifstream read1, read2;

read1.open("test.txt", ios::in);
read2.open("test2.txt", ios::in);
ofstream outFile("outputfile.txt", ios::out | ios::app);


if(!read1 || !read2){
    cerr << "One file is missing" << endl;
    exit(1);

}

else {
    while(getline(read1, line1))
    {
        outFile << line1;

    }
    while(getline(read2, line2))
    {
        outFile << line2 << endl;
    }

Thanks a lot guys!非常感谢你们!

iterate the strings and compare character vs. character?迭代字符串并比较字符与字符? This would allow you to achieve what you're looking for.这将使您能够实现您正在寻找的东西。

This example obviously does not have exception handling (eg different string lengths):这个例子显然没有异常处理(例如不同的字符串长度):

std::string corn = "I eat Corn!";
std::string rice = "I eat Rice!";

int main()
{
    for (size_t i = 0; i < corn.length(); i++)
    {
        if (corn[i] != rice[i])
        {
            rice[i] = corn[i];
        }
    }
    std::cout << rice;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM