tellg() vs. tellp()

Hey there, please somebody explain why the output is 7 and not 8:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ofstream outFile("myfile.txt",ios::out | ios::binary);
    outFile << "this is a test";
    outFile.close();
    char temp[20];
    ifstream inFile("myfile.txt",ios::in | ios::binary); // open in stream
    inFile.seekg(3,ios::cur); // move 3 steps ahead
    inFile.get(temp,5);
    puts(temp); // print: s is
    cout << inFile.tellg(); // location is 8, but will print "7"

    return 0;
}


Here the output is 16, as expected:
1
2
3
ofstream outFile("myfile.txt",ios::out | ios::binary);
outFile << "this is 16 chars";
cout << outFile.tellp(); // print 16 
Last edited on
When you pass 5 to the get function you are saying that the function should write at most 5 characters to the array. In your program it writes the characters 's', ' ', 'i', 's' and '\0'.

'\0' is a null-character that is used to mark the end of strings. The get function always put this character at end of the string so if you pass 5 it means it can at most extract 4 characters from the stream. The last position is needed for the null-character.

3 + 4 = 7
Last edited on
Thank you, Peter!
Topic archived. No new replies allowed.