Connecting Tech Pros Worldwide Help | Site Map

problem with fstream

Newbie
 
Join Date: Dec 2006
Posts: 6
#1: Dec 7 '06
Hi,

I have very strange problem with std::fstream. I want to read a simple two-column space-separated file with the following code:

#include <iostream>
#include <fstream>

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.    std::ifstream file("file.txt");
  4.    unsigned long oldval;
  5.    unsigned long newval;
  6.  
  7.    while(!file.eof()) {
  8.       file >> oldval;
  9.       file >> newval;
  10.       std::cout << oldval << " " << newval << std::endl;
  11.    }
  12. }
The file.txt contains ten lines only:

Expand|Select|Wrap|Line Numbers
  1. 3036679276 4677957
  2. 3233819949 6457113
  3. 3602920021 7347886
  4. 6236944672 16846074
  5. 2487223488 3069408
  6. 2818574689 4363018
  7. 5419052468 13941073
  8. 9172944933 31529903
  9. 2818574690 4363020
  10. 9172944938 31529909
As output, I get an endless printing of the 3rd line. I have tried a lot of variants, like:

Expand|Select|Wrap|Line Numbers
  1. while(file>>oldval>>newval)
  2. while(file.good())
and I always get the same behavior. It looks like the seek internal pointer of fstream is not moving. Any clues about this? I'm in RH with GCC3.4. Thanks for your time.
Newbie
 
Join Date: Dec 2006
Posts: 6
#2: Dec 7 '06

re: problem with fstream


Hi,

Still trying to solve this. I'm trying reading each line and then, with std::stringstream, pass

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.    std::ifstream file("file.txt");
  4.    unsigned long oldval;
  5.    unsigned long newval;
  6.    std::string line;
  7.  
  8.    while(!file.eof()) {
  9.       std::getline(file, line);
  10.       std::stringstream linestream(line);
  11.       linestream >> oldval;
  12.       linestream >> newval;
  13.       std::cout << oldval << " " << newval << std::endl;
  14.    }
  15. }
I get the following:

Expand|Select|Wrap|Line Numbers
  1. 3036679276 4677957
  2. 3233819949 6457113
  3. 3602920021 7347886
  4. 3602920021 7347886
  5. 2487223488 3069408
  6. 2818574689 4363018
  7. 2818574689 4363018
  8. 2818574689 4363018
  9. 2818574690 4363020
  10. 2818574690 4363020
  11. 2818574690 4363020
????? I don't get it :S Any ideas??? I'm starting to believe that my computer is possessed
Newbie
 
Join Date: Dec 2006
Posts: 6
#3: Dec 7 '06

re: problem with fstream


Hi,

Still trying to solve this... I've printed the put pointer, to know if its moving:

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.    std::ifstream file("file.txt");
  4.    unsigned long oldval;
  5.    unsigned long newval;
  6.  
  7.    while(!file.eof()) {
  8.       file >> oldval;
  9.       file >> newval;
  10.       std::cout << oldval << " " << newval << std::endl << file.tellg() << std::endl;
  11.    }
  12. }
I get always -1. I also reinstalled gcc.
Reply