0

I have two files names.txt and addresses.txt, both of them have the same number of lines.

I want to read these two files at the same time, and for each line print a name followed by an address. But I read that I can't have two ifstreams at the same time.

I'm not looking for alternative ways of doing this, I'd like to do it this way

8
  • You can not have them at the exact same instant in time but you can have them very close Commented Dec 24, 2017 at 2:05
  • 4
    You can have 2 ifstreams at the same time. There’s no problem here whatsoever Commented Dec 24, 2017 at 2:06
  • 1
    "but I read that I can't have 2 ifstreams at the same time." - Your code CAN have many ifstreams open at the same time. There is some limit, but it is quite a bit more the 2. Commented Dec 24, 2017 at 2:38
  • @JakeFreeman - Did the post change? I can not find the word 'exact' anywhere but these comments. Commented Dec 24, 2017 at 2:40
  • 2
    Whatever you read that said you can't have two ifstream objects at the same time was wrong. Commented Dec 24, 2017 at 2:47

1 Answer 1

5

To read two fstreams at the same time for the purpose of this example would be this.

fstream names("names.txt"); fstream add("addresses.txt"); string n, a; while(getline(names, n) && getline(add, a)) { cout<<n<<" "<<a<<endl; } 

Hope this helps.

Sign up to request clarification or add additional context in comments.

5 Comments

this actually can be considered by reading at the same time, since nothing happens in between reading one file and another.
@Fureeish fair enough though without complex threading it cannot be at the exact same time.
Even with complex threading it cannot be done at the same time. Even setting a fixed timepoint to begin execution of reading does not guarantee it to start simultaneously
Even with threading your hardware may not support it. I mean a single hard drive will not read 2 files at the exact same time.
@Fureeish I updated my answer to reflect you suggestion