Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从文件读取时,tellg()的行为如何?_C++_Fstream - Fatal编程技术网

C++ 从文件读取时,tellg()的行为如何?

C++ 从文件读取时,tellg()的行为如何?,c++,fstream,C++,Fstream,我正在尝试使用fstream读取文件。我正在尝试的文件 阅读包含以下内容: 1200 1000 980 890 760 我的代码: #include <fstream> #include <iostream> using namespace std; int main () { fstream file("highscores.txt", ios::in | ios::out); if (!file.is_open()) {

我正在尝试使用
fstream
读取文件。我正在尝试的文件 阅读包含以下内容:

1200
1000
980
890
760
我的代码:

#include <fstream>
#include <iostream>

using namespace std;

int main ()
{
    fstream file("highscores.txt", ios::in | ios::out);

    if (!file.is_open())
    {
        cout << "Could not open file!" << endl;
        return 0;
    }

    int cur_score; 

    while (!file.eof())
    {
        file >> cur_score;
        cout << file.tellg() << endl;
    }
}
为什么在第一次读取
tellg()后返回9,
第一次读取的是数字(1200),即4个位置
我知道有
\r
\n
所以这是6个位置。也。如果我在我的文件中添加更多的数字,
tellg()

第一次读取后返回一个较大的数字。

如果使用文本编辑器以UTF8格式保存文件,文件开头可能会有一个字符。此BOM表的长度为3个字符,因此添加到6个字符后,将为9个字符

如果要确定,请检查文件的开头,包括:

fstream file("highscores.txt", ios::in | ios::out | ios::binary);
if(file) {
    char verify[16];
    file.read(verify, sizeof(verify));
    int rd = file.gcount();
    for(int i = 0; i<rd; i++) {
        cout << hex << setw(2) << (int)verify[i] << " ";
    }
    cout <<dec << endl;
}
fstream文件(“highscores.txt”,ios::in | ios::out | ios::binary);
如果(文件){
字符验证[16];
read(verify,sizeof(verify));
int rd=file.gcount();

对于(int i=0;我不使用。@πάνταῥεῖ: 没错。请注意,OP有五个输入数据,但有六行输出。Tsk Tsk。没有其他空格,我确保每个数字后都没有空格…我不知道此信息是否有用,但如果您将其设置为csv,它将正常工作…tellg()的结果投票关闭会更有意义。@KerrekSB在windows下使用MingW编译并读取以文本模式打开的CRLF文件时,问题会重现。但是tellg()的依赖性呢txt文件中的行数结果…我的意思是,如果我在txt文件中再添加一个数字,我将得到10而不是9?您是否完全运行问题中发布的代码?在哪个操作系统上执行此操作?如果使用上面的验证代码,结果如何?@ehabibrahim您是否使用文本编辑器将行添加到文件中?W我有一个?我使用win7并运行确切的代码…你的代码的结果是:313230D30130D393830AD393830DOK!我现在用windows下的migw复制了它。
fstream file("highscores.txt", ios::in | ios::out | ios::binary);
if(file) {
    char verify[16];
    file.read(verify, sizeof(verify));
    int rd = file.gcount();
    for(int i = 0; i<rd; i++) {
        cout << hex << setw(2) << (int)verify[i] << " ";
    }
    cout <<dec << endl;
}