在c++中保存Int数据到文本文件

Save Int Data into Text File in C++

本文关键字:文本 文件 数据 Int c++ 保存      更新时间:2023-10-16

我正在将数据保存到文本文件中并将其与另一个文本文件进行比较。下面是我编写的代码:

    ofstream outfile;
    outfile.open("Data",ios::out | ios :: binary);
    for(x=0; x<100; x++)
    {
       printf("data- %xn", *(((int*)pImagePool)+x));
       int data =  *(((int*)pImagePool)+x);
       //outfile<<(reinterpret_cast<int *>(data))<<endl;    
       outfile<<(int *)data<<endl;     
    }

printf读取的结果是24011800,从文本文件读取的结果是0x24011800

为什么会出现0x ?我们能把它取出来吗?

reinterpret_cast<int *> & (int *)之间的区别是什么,但两者都给出了相同的结果?

这是因为您将其强制转换为指针,因此输出将是指针。

由于data是一个正常的值变量,就像往常一样写:

outfile << data << 'n';

我还建议你在编程c++时停止使用printf,没有理由使用它。使用std::cout:

代替输出
std::cout << "data- " << *(((int*)pImagePool)+x) << 'n';

或者如果你想要十六进制输出

std::cout << "data- " << std::hex << *(((int*)pImagePool)+x) << 'n';

"%x"是十六进制数的说明符。检查此表:http://www.cplusplus.com/reference/cstdio/printf/

使用"%d"输出小数。

编辑:关于选角,请参阅:

Reinterpret_cast与c风格的强制转换

这是一个使用ofstream函数的非常简单的例子。最复杂的部分是传递给open的参数,特别是std::ios::out,它指定了文件的方向。您还可以使用std::ios:in和cin一起从文件中读取。

// ex5.cpp
#include <string>
#include <iostream>
#include <fstream>
#include "hr_time.hpp"
#include >ios>
int main(int argc, char * argv[])
{
    CStopWatch sw;
    sw.startTimer() ;
    std::ofstream f;
    f.open("test.txt",std::ios::out ) ; 
    for (int i=0;i<100000;i++)
    {
      f << "A very long string that is number " << i << std::endl;
    }
    f.close() ;
    sw.stopTimer() ;
    std::cout << "This took " << sw.getElapsedTime() << " seconds" << std::endl;
    return 0;
}