I/O Streams

Hi im trying to read the first line of the following text file after its been read once all the way with good() method. The following is my text file named "test.dat"


advanced
weight
weight
weight
weight


The following is my code:
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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    string filename = "test.dat"; 
    
    inFile.open(filename.c_str());
      
    int sum = 0;
    while(inFile.good())
    {
       string w, weg = "weight";
       inFile >> w;
       
       if (w == weg)
       { 
          sum++  ;   // sum is the total number of times weight appears in the data file
       }
    }

   cout << sum << endl;

   inFile.seekg(0L,ios::beg);
   string were;
   inFile >> were;
   cout << were;     // i want were to be the string "advanced"

   system("pause");
   return 0;
} 
Last edited on
sum = ++Summ ;
This is going to add 1 for the first occurrance, 2 for the second occurrance, etc.
Why not just:
sum++;

1
2
inFile >> were;
cout << were; // i want were to be the string "advanced" 

If you're not getting "advanced", what are you getting?

Please use code tags (<> button) when posting code.

I'm just getting a 4, which is the number of times weight is encounter. But i want it to display the following:

4
advanced
Last edited on
Wasn't this asked earlier today? inFile.clear() before seekg(), you can't seek a stream that has the failbit set.

(also, while(inFile.good()) is an error, albeit harmless in this case since the extra iteration of the loop simply clears w and fails the "if" test)
Last edited on
Problem solved! Thank you Cubbi.

I don't know what a failbit set is.
Last edited on
Topic archived. No new replies allowed.