Bay 12 Games Forum

Please login or register.

Login with username, password and session length
Advanced search  

Author Topic: Is there an easy C++ equivalent to printf("%.8x",integer);?  (Read 3177 times)

qwertyuiopas

  • Bay Watcher
  • Photoshop is for elves who cannot use MSPaint.
    • View Profile
    • uristqwerty.ca, my current (barren) site.

I have been avoiding C++ for a variety of reasons, and recently decided to use it for a program because of it's easy string concatenation(C requires you to resize the string before concatenation, and I am working with situations where I can not simply predict the required padding, as it will most likely either be way too large or will be reached sometime), but I would like to give output in base 16 rather than base 10.
Google failed me by either giving a result that didn't work and one that would probably work but required creating a class and other undesireable stuff.

So, I would like to know if eithe printf() is compatible with ofstream, or a way to output fixed precision hexadecimal rather than integers.

Edit: I realized a solution:
sprintf to a char[10](reused to avoid malloc and free) and << that into the string/file.

Still, knowing the "proper" way would be nice.

Edit again:
sprintf() to a global temp worked perfectly, at least the way I did it so I just use
out<<"\n["<<hexstr(x)<<"] \"";
Where x is an int, and out is an ofstream.

Still would like to know if there is a better version, as this way requires either passing the format string or writing a function for common formats(although I could do both, there probably is a better way).
« Last Edit: June 22, 2009, 07:06:27 pm by qwertyuiopas »
Logged
Eh?
Eh!

Alexhans

  • Bay Watcher
  • This is toodamn shortto write something meaningful
    • View Profile
    • Osteopatia y Neurotonia
Re: Is there an easy C++ equivalent to printf("%.8x",integer);?
« Reply #1 on: June 23, 2009, 10:16:26 am »

I may have misunderstood the question... I'll read it again later and see if I can help.

short thought...

cant you use <iomanip> header to format and use cin cout if its something simple?
« Last Edit: June 23, 2009, 10:23:46 am by Alexhans »
Logged
“Eight years was awesome and I was famous and I was powerful" - George W. Bush.

qwertyuiopas

  • Bay Watcher
  • Photoshop is for elves who cannot use MSPaint.
    • View Profile
    • uristqwerty.ca, my current (barren) site.
Re: Is there an easy C++ equivalent to printf("%.8x",integer);?
« Reply #2 on: June 23, 2009, 11:31:45 am »

The problem is not getting the output out, but getting it out in the desired format.
Generally in a way that works for file output as well as standard output.
In a way better than using sprintf(); to a temporary string to get the desired formatting.
Logged
Eh?
Eh!