ifstream Problem..

Basically I open the text file (test.txt) and that contains a few words only and the first time it is opened and read line by line it works. I then seekg() to the first line (0) and then try to repeat but adding to a dynamic string array..

It doesnt do this but instead it follows the program process down to the end. No Errors, nothing.

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <fstream>
#include <string>
#include <new>

int main() {
    using namespace std;
    string tmpline, filename;
    int i = 0;
    
    cout << "Enter file name: ";
    getline(cin, filename);

    ifstream file(filename.c_str());

    if (file.is_open()) {
       while (! file.eof()) {
             getline(file, tmpline);
             //cout << tmpline << endl
             i++;
       }
       cout << "File contains: " << i << " Lines." << endl;
       file.seekg(0);

       string * lines;
       lines = new (nothrow) string[i];
       int n = 0;
       while (! file.eof()) {
             getline(file, lines[n]);
             n++;
       }
       file.close();
       
       for (int d = 0; n > d; d++) {
           cout << lines[n] << endl;
       }
       delete[] lines;
    } else {
      cout << "Unable to open file" << endl;
    }
    int grab; // just so i can tap 0 and it exit
    cin >> grab; // so i could read the screen..  
    
    return(0);
}


I hope someone can help, or tell me how to be more efficent too..

- Elliot
if you do:
file.clear(); before doing file.seekg(0);
then that should do the trick.

ps. it will crash doing the for loop starting at line 34 - i'll leave that to you to find out why :-)
Haha yes, I sorted.

Sorry to be a bother, I've never seen file.clear() anywhere yet >.>

Cheers :)
Last edited on
I also encountered this kind of problems before. Then I tried to read the fstream and find this clear() functions, I used it in my program and problems solved.

To use file.clear() is the right way to solve such problems. It seems fstream will set some flags, which caused some problems. Use clear() can reset them all.
Topic archived. No new replies allowed.