c++seekg似乎返回了一个十六进制地址,而不是.txt文件中的实际字符

c++ seekg seems to be returning a hex address instead of the actual char from .txt file

本文关键字:txt 文件 字符 十六进制地址 返回 一个 c++seekg      更新时间:2023-10-16

我剪下了一段简单的代码,我正在学习如何使用c++库阅读纯文本。在与程序相同的目录中,我得到了包含ASCII纯文本行的text1.txt。在我运行代码后,我希望在textOut.txttext1.txt获得相同的字符。相反,在textOut.txt中,我有100行

0x7ffdf21fd0180x7ffdf21fd0180x7ffdf21fd0180x7ffdf21fd0180x7ffdf21fd0180x7ffdf21fd0180x7ffdf21fd0180x7ffdf21fd0180x7ffdf21fd0180x7ffdf21fd0180x7ffdf21fd0180x7ffdf21fd0180x7ffdf21fd0180x7ffdf21fd0180x7ffdf21fd0180x7ffdf21fd018

这是代码:

#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
using namespace std;
int main() {
fstream  afile;
afile.open("text1.txt", ios::in );   
ofstream outfile;
outfile.open("textOut.txt");
int counter=0;
for( counter=0;counter<100;counter++ ){
   outfile << afile.seekg(counter);
   outfile << "n";
   //printf("%dn", counter);
   }
return 0;
}

seekg返回*this,因此<<运算符在这种情况下工作是令人惊讶的。

而是使用

outfile << static_cast<char>(afile.get());

完整程序:

#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
using namespace std;
int main()
{
    fstream  afile;
    afile.open("text1.txt",ios::in);
    ofstream outfile;
    outfile.open("textOut.txt");
    int counter=0;
    for (counter=0; counter<100; counter++) {
        afile.seekg(counter);
        outfile << static_cast<char>(afile.get());
        //outfile << afile.seekg(counter);
        outfile << "n";
        //printf("%dn", counter);
    }
    return 0;
}