Deepika Sethi
Deepika Sethi

Reputation: 223

Printing hex and int together in a text file

I am trying to print hex values for member[0] and member[1] and integer values for _records in the same text file with the following code:

 std::ofstream myoutputfile;

 myoutputfile << std::hex << (int)(unsigned char)_member[0] << ' ';

 myoutputfile << std::hex << (int)(unsigned char)_member[1] << ' ';

 myoutputfile<<_records << std::endl;

But this code prints _records in hex too. I have tried:

myoutputfile<<(int)_records << std::endl;

But still it prints it in hex.

Can anyone help please.

Upvotes: 2

Views: 108

Answers (4)

Praetorian
Praetorian

Reputation: 109119

Set the format back to decimal using std::dec

myoutputfile<< std::dec << _records << std::endl;

As you've discovered, the base format specifiers are sticky, so there's no need to specify std::hex each time. Your code could be rewritten as follows to achieve the same effect.

std::ofstream myoutputfile;
myoutputfile << std::hex 
  << (int)(unsigned char)_member[0] << ' '
  << (int)(unsigned char)_member[1] << ' '
  << std::dec << _records << std::endl;

You could also have the resetting to previous state done automatically by using Boost IO State Savers.

#include <boost/io/ios_state.hpp>
#include <ios>
#include <iostream>
#include <ostream>

int  main()
{
    auto hex_printer = [](std::ostream& os, unsigned char byte) {
        boost::io::ios_flags_saver  ifs(os);
        os << std::hex << static_cast<unsigned>(byte) << ' ';
    };

    hex_printer(std::cout, 'A');
    std::cout << 42 << '\n';
}

Live demo

Upvotes: 4

Pandrei
Pandrei

Reputation: 4951

you can use fprintf, which prints formatted text:

frintf("%x %x %d\n",_member[0],_member[0],_records);

Hope this helps

Upvotes: 0

Mad Physicist
Mad Physicist

Reputation: 114290

std::hex tells an ostream to print everything in hex from that point on. The equivalent that will return it to decimal is std::dec. Try the following:

std::ofstream myoutputfile;
myoutputfile << std::hex;
myoutputfile << _member[0] << ' ';
myoutputfile << _member[1] << ' ';
myoutputfile << std::dec << _records << std::endl;

Check out http://www.cplusplus.com/reference/ios/hex/ as an additional reference.

Upvotes: 1

user335938
user335938

Reputation:

The base that's use for conversion from numbers to text is a state of the output stream rather than a function of the input type. You need to do:

myoutputfile<< std::dec << _records << std::endl;

This changes the state of the output stream to put _records using decimal.

Upvotes: 2

Related Questions