Decimal value of: cout << dec << boost::this_thread::get_id() - c++

Is it possible to cout thread::id in a decimal or octal format?
std::cout << std::showbase;
cout << dec(or oct) << boost::this_thread::get_id()
I got always hex, for example 0xdf08.

You should be able to specify what output format you want by using standard I/O manipulators:
#include <iomanip>
// ...
std::cout << std::oct << boost::this_thread::get_id() << std::endl;
// ^^^^^^^^
// Octal
std::cout << std::dec << boost::this_thread::get_id() << std::endl;
// ^^^^^^^^
// Decimal
std::cout << std::hex << boost::this_thread::get_id() << std::endl;
// ^^^^^^^^
// Hexadecimal
However, notice that a thread::id does not need to be a number. Also, it may be a number but may be printed to the standard output in a different way than just inserting that number into std::cout.
The C++11 Standard specification the overload of operator << accepting an std::thread::id (which I assume to behave similarly to Boost's correspondent overload for boost::thread::it), says:
[...] Inserts an unspecified text representation of id into out.
This means the representation may not be a number at all, in which case formatting manipulators such as std::hex,std::dec, or std::oct may not have any influence on it.

Related

How to automatically set stream mode back to default [duplicate]

This question already has answers here:
Restore the state of std::cout after manipulating it
(9 answers)
Closed 4 years ago.
C++ steam objects have state. If one write a piece of code like
using namespace std;
cout << hex << setw(8) << setfill('0') << x << endl;
forgetting setting the stream state back. This will cause problems in some other unrelated codes. It's tedious to do "set" and "set back" pair matching. Besides from that, it seems to me it's also against convention behind RAII.
My question is: is it possible, with only a thin layer of wrapping, to make those state manipulations RAII-like. That is, right after the end of an expression by semicolon, stream state is automatically set back to default.
Update: Following the link provided by #0x499602D2, one workaround might be something like
#include <boost/io/ios_state.hpp>
#include <ios>
#include <iostream>
#include <ostream>
#define AUTO_COUT(x) {\
boost::io::ios_all_saver ias( cout );\
x;\
}while(0)
Then one can use the macro like
AUTO_COUT(cout << hex << setw(8) << setfill('0') << x << endl);
BTW, it might be a good idea to add a lock field to those saver class of boost::io::ios_state, in case funny things occur in a multi-threading program. Or they have already done so?
I'm going to suggest an alternative approach. The manipulators apply to the std::[i|o]stream instance, but they do nothing with regards to the std::[i|o]streambuf which is managed by that std::[i|o]stream.
Therefore, you can create your own std::[i|o]stream, which will have its own formatting state, but writing to the same buffer std::cout uses:
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::hex << 32 << "\n";
std::ostream os(std::cout.rdbuf());
os << 32 << "\n" << std::hex;
std::cout << std::dec;
os << 32 << "\n";
std::cout << 32 << "\n";
}
Output:
20
32
20
32
Live on Coliru
This uses only features from standard library, and since the original stream is not touched, applying manipulators is trivially thread safe (because each thread operates on a different stream). Now, the actual writes and reads' thread safety depends on the thread safety of the managed stream buffer.
I once wrote a utility class for my personal use. (I don't know whether it is as perfect as the boost code probably is but it worked for me – so, I dare to share.)
#include <iostream>
#include <iomanip>
/** provides a helper class to work with streams.
*
* It stores current format states of a stream in constructor and
* recovers these settings in destructor.
*
* Example:
* <pre>
* { // backup states of std::cout
* IOSFmtBackup stateCOut(std::cout);
* // do some formatted output
* std::cout
* << "dec: " << std::dec << 123 << std::endl
* << "hex: " << std::hex << std::setw(8) << std::setfill('0')
* << 0xdeadbeef << std::endl;
* } // destruction of stateCOut recovers former states of std::cout
* </pre>
*/
class IOSFmtBackup {
// variables:
private:
/// the concerning stream
std::ios &_stream;
/// the backup of formatter states
std::ios _fmt;
// methods:
public:
/// #name Construction & Destruction
//#{
/** constructor.
*
* #param stream the stream for backup
*/
explicit IOSFmtBackup(std::ios &stream):
_stream(stream), _fmt(0)
{
_fmt.copyfmt(_stream);
}
/// destructor.
~IOSFmtBackup() { _stream.copyfmt(_fmt); }
// disabled:
IOSFmtBackup(const IOSFmtBackup&) = delete;
IOSFmtBackup& operator=(const IOSFmtBackup&) = delete;
//#}
};
int main()
{
{ // backup states of std::cout
IOSFmtBackup stateCOut(std::cout);
// do some formatted output
std::cout
<< "dec: " << std::dec << 123 << std::endl
<< "hex: " << std::hex << std::setw(8) << std::setfill('0')
<< 0xdeadbeef << std::endl
<< "123 in current: " << 123 << std::endl;
} // destruction of stateCOut recovers former states of std::cout
// check whether formatting is recovered
std::cout << "123 after recovered: " << 123 << std::endl;
return 0;
}
Compiled and tested on ideone (life demo).
Output:
dec: 123
hex: deadbeef
123 in current: 7b
123 after recovered: 123

What does cout << std::ios::hex do?

This question comes from a bug that I got into recently. I was trying to save some integer values to file as hex. As an example, this is what I should do:
cout << std::hex << value << endl; // (1)
But by mistake, I use it as the following:
cout << std::ios::hex << value << endl; // (2)
The compiler does not complain but obviously the result is not correct. I was trying a couple more values randomly and it seems that (2) actually give partially correct result except that it append 800 as a prefix. I don't understand where the 800 is coming from and I don't see a good reference anywhere. Can anybody explain what's happening under the hood?
cout << std::hex << 255 << endl; // output: FF
cout << std::ios::hex << 255 << endl; // output: 800ff
cout << std::hex << 135 << endl; // output: 87
cout << std::ios::hex << 135 << endl; // output: 80087
cout << std::hex << 11 << endl; // output: b
cout << std::ios::hex << 11 << endl; // output: 800b
This is actually std::ios_base::hex. It's an implementation-defined bitmask. Internally, the stream has an integer called fmtflags where it stores the current state of the formatting.
In your implementation, hex is the flag 0x800. Other flags will indicate whether it's in scientific notation mode, whether boolalpha is on, etc. etc.
The std::hex function sets the std::ios_base::hex flag in fmtflags.
So your output is the integer value of this flag (in hex since you sent std::hex previously).
std::hex is a manipulator, i.e., it is a function with a specific signature:
std::ios_base& hex(std::ios_base& stream) {
stream.setf(std::ios_base::hex, std::ios_base::basefield);
return stream;
}
There are some special output operators defined for stream to process manipulators. For the version operating on references to std::ios_base there is (ignoring that the operator is actually a function template):
std::ostream& operator<< (std::ostream& out, std::ios_base&(*manip)(std::ios_base&));
When used with a stream, the manipulator function is being called and it sets a specific format flag, in this case std::ios_base::hex (which is how std::ios::hex is actually defined). Since std::ios_base::hex is a member of a group of flags (the others are std::ios_base::dec and std::ios_base::oct) setting it also needs to clear any potential other flag in the group. Thus, setf() is called with a mask (std::ios_base::basefield) to clear any of the other potentially set flags.
The format flags std::ios_base::fmtflags is a bitmask type. The value std::ios_base::hex is one of the values. When formatting it you'll get some number, most likely a power of 2 (however, it doesn't have to be a power of 2). The value you see is simply 0x800 (i.e. 2048) printed using hex notation: setting any of the formatting flags (other than the width()) is sticky, i.e., they remain until the flag is unset. If you want to see the value 2048 (for the implementation you are using) you'd use
std::cout << std::dec << std::ios_base::hex << "\n"; // 2048
std::cout << std::hex << std::ios_base::hex << "\n"; // 800
std::cout << std::showbase << std::ios_base::hex << "\n"; // 0x800
The last line sets the flag showbase which indicates the base of an integer value with a prefix:
no prefix => decimal
a leading 0x => hexadecimal
a leading 0 (but no x) => octal
std::hex is a special object that, when applied to a stream using operator<<,
sets the basefield of the stream str to hex as if by calling str.setf(std::ios_base::hex, std::ios_base::base field)
std::ios::hex (aka std::ios_base::hex) is the actual bitmask value that gets passed to the setf method. Its value is implementation defined, and it seems to be 0x800 in your case.

std::cout gives different output from qDebug

I am using Qt, and I have an unsigned char *bytePointer and want to print out a number-value of the current byte. Below is my code, which is meant to give the int-value and the hex-value of the continuous bytes that I receive from a machine attached to the computer:
int byteHex=0;
byteHex = (int)*bytePointer;
qDebug << "\n int: " //this is the main issue here.
<< *bytePointer;
std::cout << " (hex: "
<< std::hex
<< byteHex
<< ")\n";
}
This gives perfect results, and I get actual numbers, however this code is going into an API and I don't want to use Qt-only functions, such as qDebug. So when I try this:
int byteHex=0;
byteHex = (int)*bytePointer;
std::cout << "\n int: " //I changed qDebug to std::cout
<< *bytePointer;
std::cout << " (hex: "
<< std::hex
<< byteHex
<< ")\n";
}
The output does give the hex-values perfectly, however the int-values return symbols (like ☺, └, §, to list a few).
My question is: How do I get std::cout to give the same output as qDebug?
EDIT: for some reason the symbols only occur with a certain Qt setting. I have no idea why it happened but it's fixed now.
As others pointed out in comment, you change the outputting to hex, but you do not actually set it back here:
std::cout << " (hex: "
<< std::hex
<< byteHex
<< ")\n";
You will need to apply this afterwards:
std::cout << std::dec;
Standard output streams will output any character type as a character, not a numeric value. To output the numeric value, convert to a non-character integer type:
std::cout << int(*bytePointer);

C++ precision - behaviour of setprecision

As I understand it the setprecision function specifies the minimal precision but when I run the following code I get only 3 numbers after the decimal point:
int main()
{
double a = 123.4567890;
double b = 123.4000000;
std::cout << std::setprecision(5) << a << std::endl; // Udesireble
std::cout.setf(std::ios::fixed);
std::cout << std::setprecision(5) << a << std::endl; // Desireble
std::cout << std::setprecision(5) << b << std::endl; // Udesireble
std::cout.unsetf(std::ios::fixed);
std::cout << std::setprecision(5) << b << std::endl; // Desireble
return 0;
}
which prints:
123.46 // Udesireble
123.45679 // Desireble
123.40000 // Udesireble
123.4 // Desireble
Is there any way I can avoid checking the number of digits after the decimal point myself in order to know whether to set fixed ?
My impression is that you will need to format to string first, and then replace trailing zeros with spaces.
For the streams, you can use two functions.
setfill(char_type c), which set the character to write, to match with the number of needed character (more information here)
There is the setw(int) function, which set the width of field of the value to display. (documentation here )
Using these functions, you may have a solution

How to set up C++ Number Formatting to a certain precision?

I understand that you can use iomanip to set a precision flags for floats (e.g. have 2.0000 as opposed to 2.00).
Is there a way possible to do this, for integers?
I would like a hex number to display as 000e8a00 rather than just e8a00 or 00000000 rather than 0.
Is this possible in C++, using the standard libraries?
With manipulators:
std::cout << std::setfill('0') << std::setw(8) << std::hex << 0 << std::endl;
Without manipulators:
std::cout.fill('0');
std::cout.width(8);
std::cout.setf(std::ios::hex, std::ios::basefield);
std::cout << 42 << std::endl;
You can also do this with boost::format, which I find often saves typing:
std::cout << boost::format("%08x\n") % 0xe8a00;
It also allows for some nice code reuse, if you have multiple places you need to do the same formatting:
boost::format hex08("%08x");
std::cout << hex08 % 0xe8aa << std::endl;