加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – ifstream tellg()没有返回正确的位置

发布时间:2020-12-16 03:47:04 所属栏目:百科 来源:网络整理
导读:代码如下: 代码: #include iostream#include fstreamusing 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 ; retur
代码如下:

代码:

#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;
}

文件内容:

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为什么会这样?

解决方法

这似乎更像是编译器错误(可能是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;
}

以下是输出: –

在图像中,inpstr.exe是从Visual Studio的cl生成的,而inp.exe是从g生成的(gcc版本4.6.1(tdm-1))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读