0

I working on saving Data into text file and compare it with another text file. Below is the code I worked on:

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

The result from printf is 24011800 and result read from text file is 0x24011800

Why there is 0x appeared? Do we able to remove it?

What is the difference between reinterpret_cast<int *> & (int *) but both giving the same result?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
WenJuan
  • 624
  • 1
  • 8
  • 21

3 Answers3

3

It's because you cast it as a pointer, so the output will be a pointer.

Since data is a normal value variable, just write it as usual:

outfile << data << '\n';

I also recommend you stop using printf when programming C++, there no reason to use it. Instead output using std::cout:

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

Or if you want hexadecimal output

std::cout << "data- " << std::hex << *(((int*)pImagePool)+x) << '\n';
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

"%x" is a specifier for a hexadecimal number. Check this table: http://www.cplusplus.com/reference/cstdio/printf/

Use "%d" to output a decimal.

EDIT: About the casting, see this:

Reinterpret_cast vs. C-style cast

Community
  • 1
  • 1
Ben
  • 1,816
  • 1
  • 20
  • 29
  • If you feel this solved your problem, mark it as the correct answer or upvote it so it stays at the top. – Ben Mar 26 '14 at 08:36
0

This is a very simple example using the ofstream f. The most complicated part are the parameters passed to the open, specifically std::ios::out which specifies the file direction. You could also use std::ios:in for reading from a file along with 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;
}