how to check if "rewind" works?

The program is supposed to read the number of vowels and the number of consonants in an external file (".txt") which it does, but I need to be able to "rewind"/go back to the start of the file, and I found a way to do this but am not sure how to check it?

Here is the 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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()  

{ 

int x = 0; 
int y = 0;  	


if (inf.is_open()) {
    cout << "File is open." << endl;
   } 
else {
    cerr << "File not found - terminating." << endl;
   }

cout << "Number of Vowels: " << n << endl;
cout << "Number of Consonants: " << c << endl;


inf.clear();
inf.seekg(0, ios::beg);	
cout << sentence << endl;
inf.close();

return 0 ;
}

Last edited on
Well, it's not working. You closed the file on line 39. You can't move a file pointer if there's no open file.
OK thanks - but if I am to test if the rewind is working, how would I do that? Use a cout statement to have it print the first sentence of the file?
Yes - printing out the first line would be just fine for testing that :)

All the best,
NwN
@NwN Thank you for answering my question!!! :)
I corrected my code to the following:

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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()  

{ 

int x = 0; 
int y = 0;  	


if (inf.is_open()) {
    cout << "File is open." << endl;
   } 
else {
    cerr << "File not found - terminating." << endl;
   }

cout << "Number of Vowels: " << n << endl;
cout << "Number of Consonants: " << c << endl;


inf.clear();
inf.seekg(0, ios::beg);	
cout << sentence << endl;
inf.close();

return 0 ;
}


Either I am not testing it correctly, or I am not rewinding it correctly:

Output:

File is open.
Number of Vowels: 30
Number of Consonants: 1003


Should I put the clear after the rewind?
Last edited on
Because sentence still equals the last line. You moved the pointer (seekg) back to the beginning, but printed out the last line again. You need to read from the file (inf) to prove that you're back at the beginning, not use data already stored in a variable.
Ahhh. Thank you.
1
2
3
4
5
6
7
8
9
10
11
do {
    getline (inf,sentence);
    c += sentence.length();
    n++;
}
//sentence contains the last sentence in file (Fallen cold and dead)

inf.clear();
inf.seekg(0, ios::beg);
cout << sentence << endl;  //sentence is still containing the last sentence
inf.close();


You should put getline (inf,sentence); after rewind and before cout << sentence << endl;

something like
1
2
3
4
5
inf.clear();
inf.seekg(0, ios::beg);
getline (inf,sentence);
cout << sentence << endl; 
inf.close();
Last edited on
Topic archived. No new replies allowed.