代码如下:
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
int id;
char name[50];
ifstream myfile("savingaccount.txt"); //open the file
myfile >> id;
cout << myfile.tellg(); //return 16? but not 7 or 8
cout << id ;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
1800567 Ho Rui Jang 21 Female Malaysian 012-4998192 20 , Lorong 13 , Taman Patani Janam Melaka Sungai Dulong
1.)我希望tellg()返回7或者8从第一行开始1800567是7位数,所以流指针应该放在这个数字之后和字符串之前"Ho Rui Jang",但是tellg()返回16.为什么会这样?
小智 6
有同样的问题。尝试读取文件流二进制文件:
ifstream myfile("savingaccount.txt",ios::binary);
Run Code Online (Sandbox Code Playgroud)
对我有帮助
这不是编译器错误。 tellg()不保证返回距文件开头的偏移量。有一组最小的保证,例如,如果 from 的返回值tellg()传递给seekg(),文件指针将定位在文件中的相应点。
实际上,在 unix 下,tellg()确实返回距文件开头的偏移量。在 Windows 下,它返回距文件开头的偏移量,但前提是文件以二进制模式打开。
但唯一真正的保证是返回的不同值tellg()将对应于文件中的不同位置。
这似乎更像是编译器错误(可能是gcc)
使用以下代码: -
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
int id;
char name[50];
ifstream myfile("savingaccount.txt"); //open the file
cout << myfile.tellg()<<endl;
myfile >> id;
streamoff pos=myfile.tellg();
cout <<"pos= "<<pos<<'\n';
cout <<"id= " << id<<'\n' ;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
以下是输出: -

在该图像inpstr.exe被从生成Visual studio's cl而inp.exe从g++(gcc version 4.6.1 (tdm-1))