Pf
I have a question regarding file handling tellg() concept :
this is my code: I want to Ask in this string the Character 'H' is actually at 0 position so why in front of H it is being written 1 why not 0?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// 1. Setup the file
ofstream out("data.txt");
out << "HELLO WORLD"; // 11 characters
out.close();
ifstream in("data.txt");
char ch;
// 2. Initial Position (0)
cout << "Initial position: " << in.tellg() << endl;
// 3. Loop through every character
// in.get(ch) reads one char and moves the pointer forward by 1
while (in.get(ch)) {
cout << "Character [" << ch << "] read. New Position: " << in.tellg() << endl;
}
// 4. Handle the End of File (EOF)
if (in.eof()) {
cout << "Reached EOF. tellg() returns: " << in.tellg() << endl; // This will be -1
in.clear(); // Reset the 'safety switch'
cout << "After clear(), final position is: " << in.tellg() << endl; // This will be 11
}
in.close();
return 0;
}
Q2.And same this is one more code in this also the why the position of 1st character not being shown as 0?
#include<iostream>
#include<fstream>
using namespace std;
main(){
ifstream myfile;
string str;
int position;
char ch;
myfile.open("lala.txt");
while (!myfile.eof()) {
if(myfile){
// myfile>>ch;
myfile.get(ch);
position=myfile.tellg();
cout<<"Character is:"<<ch<<" "<<"at position:"<<position;
cout<<endl;
}
else{
cout<<"Something went wrong";
}}}
image.png
Q3. last Question I am having bit confusion that why
*Character is:f at position:-1*(-1 is being shown) is being shown in end I am unable to understand
Posted Apr 9, 2026, 9:22 PM UTC