c++ - 比较两个文件并发送相等的值

标签 c++

我是新来的。试图做一些我认为应该很容易但无法开始工作的事情。我有两个文件,它们在

中只有简单的数据

文件A

KIC
757137  
892010  
892107  
892738  
892760  
893214  
1026084
1435467
1026180
1026309
1026326
1026473
1027337
1160789
1161447
1161618
1162036
3112152
1163359
1163453
1163621
3123191
1164590

和文件 B

KICID
1430163
1435467
1725815
2309595
2450729
2837475
2849125
2852862
2865774
2991448
2998253
3112152
3112889
3115178
3123191
�

我想读取这两个文件,然后打印出相同的值,并忽略标题。在这种情况下,我会得到 1435467 3123191 在两者中,并且只有这些将被发送到一个新文件。 到目前为止我有

#include <cmath>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <ctime>

using namespace std;

// Globals, to allow being called from several functions

// main program

int main() {
    float A, B;

    ifstream inA("FileA"); // input stream
    ifstream inB("FileB"); // second instream
    ofstream outA("OutA.txt"); // output stream

    while (inA >> A) {
        while (inB >> B) {

            if (A == B) {
                outA << A << "\t" << B << endl;
            }
        }
    }
    return 0;
}

这只会产生一个空文档 OutA 我认为这会读取一行 FileA,然后循环遍历 FileB 直到找到匹配项,发送到 OutA,然后移动到FileA 的下一行 任何帮助将不胜感激?

最佳答案

你需要放

inB.seekg(0, inB.beg)

到外部 while 循环的末尾。否则,您将停留在 inB 的末尾,并且在处理完 inA

的第一个条目后将不会读取任何内容

关于c++ - 比较两个文件并发送相等的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25788625/

相关文章:

c++ - auto-complete-clang-async 无法按预期在 Emacs 上运行

c++ - boost::spirit 默认语义 Action 和字符串组合

c++ - 如何将这个 Boost ASIO 示例应用到我的应用程序中

python clang : Getting Template Arguments

c++ - Qt "hello world"GUI 应用程序未链接?

C++ 覆盖父结构中的数据不起作用

c++ - 防止对象切片 - C++

std::map::insert 处的 C++ 段错误

c++ - 如何在没有 STL 的情况下从二维数组中删除任何未填充的插槽?

C++ 泛型数组实现