File Handling : Getting One Extra Character!

So I was going through File handling again trying to make a big program to perform certain operations on a file but now i can't move forward because of this error :
While showing the content of the file i get one extra character at the last.

If i write : Hey It is akshat
Output is : Hey It is akshatt

This is really weird,it didn't happened the last time i worked on file handling
i know i am doing some small mistake,please help.

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
#include<fstream>
#include<iostream>
#include<string>
#include<string.h>
using namespace std ;
int main()
{
    string content ;
    char ch ;
    ofstream f1 ("Akshat.txt");
    cout<<"\nEnter The Content For The File : " ;
    getline(cin,content);
    f1 << content ;
    f1.close();
    ifstream f2 ("Akshat.txt");
    cout<<"\nThe Entered String Is : " ;
    while(f2)
    {
        f2.get(ch);
        cout<<ch;
    }
    f2.close();
    return 0 ;
}
Oh Wow,I just changed the lines 17-19 like this

1
2
3
4
 while (f2.get(ch))
{
    cout<<ch ;
}


and it solved the problem,can anyone explain why the former was showing an extra character?
Last edited on
It is because your first implementation tested the stream state after the output statement, the second snippet tests the stream state before you try to output the value.
Topic archived. No new replies allowed.