file handling in c++

I want to write a program that take a 6 digit number from 1 text file and match it with another 6 digit number in another file.
if matched display it on the screen.
help me please.....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  
#include <iostream>
#include <fstream>
using namespace std ;
int main()
{
int bondn , listn;
ifstream bonds("bond.txt") ;
ifstream lists("list.txt") ;
while ( ! bonds.eof() )
{
bonds>> bondn ;
while( !lists.eof() )
{
lists>> listn ;
if (bondn == listn)
cout<<listn <<endl ;
}
}
return 0;
}



I'm not quite sure that you fully understand your code's control flow.

You get the first number from "bond.txt" then you go through the whole file "lists.txt" in the nested while loop and you reach end of file, note that you are still in first iteration of the outer while loop, and on the second iteration of the outer while loop the nested while loop will no longer be executed because you already reached the end of file in "lists.txt".

Why don't you traverse both files simultaneously?

Side note: I recommend you use indentation.
Last edited on
Thanks dear......

Why don't you traverse both files simultaneously?
Ans: I want to search each number in bond.txt in list.txt.

tell me please how can i reach to the start of file?
Load the content of each file in a std::vector<int>. You should have a for loop to traverse the first container and a nested for loop to traverse the second container. If one file is longer than the other then the second for loop should traverse the longer std::vector<int>.

Going to the beginning of the file every time isn't efficient because reading from the disk is exponentially slower than reading from main memory.
Last edited on
can i use array instead of a vector?
Only if you know exactly how many numbers are in the text file. Use std::array instead of plain old C style arrays.
Topic archived. No new replies allowed.