I've noticed a discrepancy in the way we print pointers. gcc by default is adding 0x prefix to hex output of pointer, and Microsoft's compiler doesn't do that. showbase/noshowbase doesn't affect either of them.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
void * n = (void *)1;
cout << noshowbase << hex << n << dec << endl;
// output (g++ (GCC) 4.7.2, 5.4.0): 0x1
// output (VS 2010, 2013): 00000001
n = (void *)10;
cout << noshowbase << hex << n << dec << endl;
// output (g++ (GCC) 4.7.2, 5.4.0): 0xa
// output (VS 2010, 2013): 0000000A
n = (void *)0;
cout << noshowbase << hex << n << dec << endl;
// output (g++ (GCC) 4.7.2, 5.4.0): 0
// output (VS 2010, 2013): 00000000
return 0;
}
I assume this is implementation defined behavior and not a bug, but is there a way to stop any compiler from prepending the 0x? We are already prepending the 0x on our own but in gcc it comes out like 0x0xABCD.
I'm sure I could do something like ifdef __GNUC___ .... but I wonder if I'm missing something more obvious. Thanks
I propose that you cast to intptr and treat the input as a normal integer.
Your I/O manipulators should then work.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
void * n = (void *)1;
cout << noshowbase << hex << reinterpret_cast<intptr_t>(n) << dec << endl;
n = (void *)10;
cout << noshowbase << hex << reinterpret_cast<intptr_t>(n) << dec << endl;
n = (void *)0;
cout << noshowbase << hex << reinterpret_cast<intptr_t>(n) << dec << endl;
}
// 1
// a
// 0
(live demo)
At first I was a little surprised by your question (more specifically, by these implementations' behaviour), but the more I think about it the more it makes sense. Pointers are not numbers*, and there's really no better authority on how to render them than the implementation.
* I'm serious! Although, funnily enough, for implementation/historical reasons, the standard calls a const void* "numeric" in this context, using the num_put locale stuff for formatted output, ultimately deferring to printf in [facet.num.put.virtuals]. The standard states that the formatting specifier %p should be used but, since the result of %p is implementation-defined, you could really get just about anything with your current code.
Related
I want to do:
int a = 255;
cout << a;
and have it show FF in the output, how would I do this?
Use:
#include <iostream>
...
std::cout << std::hex << a;
There are many other options to control the exact formatting of the output number, such as leading zeros and upper/lower case.
To manipulate the stream to print in hexadecimal use the hex manipulator:
cout << hex << a;
By default the hexadecimal characters are output in lowercase. To change it to uppercase use the uppercase manipulator:
cout << hex << uppercase << a;
To later change the output back to lowercase, use the nouppercase manipulator:
cout << nouppercase << b;
std::hex is defined in <ios> which is included by <iostream>. But to use things like std::setprecision/std::setw/std::setfill/etc you have to include <iomanip>.
If you want to print a single hex number, and then revert back to decimal you can use this:
std::cout << std::hex << num << std::dec << std::endl;
I understand this isn't what OP asked for, but I still think it is worth to point out how to do it with printf. I almost always prefer using it over std::cout (even with no previous C background).
printf("%.2X", a);
'2' defines the precision, 'X' or 'x' defines case.
std::hex gets you the hex formatting, but it is a stateful option, meaning you need to save and restore state or it will impact all future output.
Naively switching back to std::dec is only good if that's where the flags were before, which may not be the case, particularly if you're writing a library.
#include <iostream>
#include <ios>
...
std::ios_base::fmtflags f( cout.flags() ); // save flags state
std::cout << std::hex << a;
cout.flags( f ); // restore flags state
This combines Greg Hewgill's answer and info from another question.
There are different kinds of flags & masks you can use as well. Please refer http://www.cplusplus.com/reference/iostream/ios_base/setf/ for more information.
#include <iostream>
using namespace std;
int main()
{
int num = 255;
cout.setf(ios::hex, ios::basefield);
cout << "Hex: " << num << endl;
cout.unsetf(ios::hex);
cout << "Original format: " << num << endl;
return 0;
}
Use std::uppercase and std::hex to format integer variable a to be displayed in hexadecimal format.
#include <iostream>
int main() {
int a = 255;
// Formatting Integer
std::cout << std::uppercase << std::hex << a << std::endl; // Output: FF
std::cout << std::showbase << std::hex << a << std::endl; // Output: 0XFF
std::cout << std::nouppercase << std::showbase << std::hex << a << std::endl; // Output: 0xff
return 0;
}
C++20 std::format
This is now the cleanest method in my opinion, as it does not pollute std::cout state with std::hex:
main.cpp
#include <format>
#include <string>
int main() {
std::cout << std::format("{:x} {:#x} {}\n", 16, 17, 18);
}
Expected output:
10 0x11 18
Not yet implemented on GCC 10.0.1, Ubuntu 20.04.
But the awesome library that became C++20 and should be the same worked once installed on Ubuntu 22.04 with:
sudo apt install libfmt-dev
or:
git clone https://github.com/fmtlib/fmt
cd fmt
git checkout 061e364b25b5e5ca7cf50dd25282892922375ddc
mkdir build
cmake ..
sudo make install
main2.cpp
#include <fmt/core.h>
#include <iostream>
int main() {
std::cout << fmt::format("{:x} {:#x} {}\n", 16, 17, 18);
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main2.out main2.cpp -lfmt
./main2.out
Documented at:
https://en.cppreference.com/w/cpp/utility/format/format
https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification
More info at: std::string formatting like sprintf
Pre-C++20: cleanly print and restore std::cout to previous state
main.cpp
#include <iostream>
#include <string>
int main() {
std::ios oldState(nullptr);
oldState.copyfmt(std::cout);
std::cout << std::hex;
std::cout << 16 << std::endl;
std::cout.copyfmt(oldState);
std::cout << 17 << std::endl;
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
Output:
10
17
More details: Restore the state of std::cout after manipulating it
Tested on GCC 10.0.1, Ubuntu 20.04.
How are you!
#include <iostream>
#include <iomanip>
unsigned char arr[] = {4, 85, 250, 206};
for (const auto & elem : arr) {
std::cout << std::setfill('0')
<< std::setw(2)
<< std::uppercase
<< std::hex
<< (0xFF & elem)
<< " ";
}
Currently when I print an address of a variable,
cout << &a, its displayed as a simple hexadecimal number, let's say: 008FFBB8.
How can I print an address with the 0x notation? e.g. 0x6FFDF4.
I tried doing:
cout << hex << &a;
but it doesn't seem to work.
There are many different solutions, the first two that came into my mind are the following:
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
int main()
{
std::cout << std::hex
<< "showbase: " << std::showbase<< 42 << '\n'
<< "noshowbase: " << std::noshowbase << 42 << '\n';
//2nd solution
std::string a{"008FFBB8"};
std::cout << "Given: " << a << '\n';
a.erase(0,2);
a = "0x"+a;
std::cout << "Edited: "<< a <<'\n';
//3rd string to int so you can use standard arithmetics
int b = std::stoul(a, nullptr, 16);
std::cout << "Represented as int: " << b << '\n';
std::cin.get();
}
Edit:
This is how it is printed after compilation with GNU GCC(g++) compiler.
The reason visual studio isn't printing it as shown on the screenshot is because visual studio tend not to use GNU GCC but its Microsoft compiler MSVC.(There are other things MSVC isn't doing as you may expect btw.) But good news: you can make it! or here:)
It is just how hex is presented in your configuration with "MSVC"
I hope that answers your question, else leave a comment :)
A simple approach
cout << "0x" << &a;
That said, given that other systems do inlude 0x in &a, in order to make it portable, you should make cout << "0x" conditional based on predefined macro that detects the systems where 0x isn't included.
A portable solution is to insert into a string stream first, then check whether the prefix was added, and concatenate if it wasn't. this also prevents possibility of 0x and the address being separated by concurrent output.
I just wanted to know why Visual Studio is not displaying this notation by default,
Because the authors of their standard library chose to do so.
so I don't have to manually do it.
I'm not sure if there is a way to change their implementation. Before asking how, I recommend considering why you think that you have to do it.
Taking inspiration ;) from MSDN and trying it on VS 2019:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
ios state(nullptr);
int a;
state.copyfmt(cout); // save current formatting
cout << "In hex: 0x" // now load up a bunch of formatting modifiers
<< hex
<< uppercase
<< setw(8)
<< setfill('0')
<< &a // the actual value we wanted to print out
<< endl;
cout.copyfmt(state); // restore previous formatting
}
Output:
In hex: 0x00AFFB44
And as for why, well...you could raise an issue on MSVC and claim parity with all other compilers and platforms if you have the data. But given that they themselves manually slipped in the 0x I'm guessing they are already comfortable with the behavior.
I want to read a chunk of data from file into stringstream, which later will be used to parse the data (using getline, >>, etc). After reading the bytes, I set the buffer of the stringstream, but I cant make it to set the p pointer.
I tested the code on some online services, such as onlinegdb.com and cppreference.com and it works. However, on microsoft, I get an error - the pointers get out of order.
Here's the code, I replaced the file-read with a char array.
#include <sstream>
#include <iostream>
int main()
{
char* a = new char [30];
for (int i=0;i<30;i++)
a[i]='-';
std::stringstream os;
std::cout << "g " << os.tellg() << " p " << os.tellp() << std::endl;
os.rdbuf()->pubsetbuf(a,30);
os.seekp(7);
std::cout << "g " << os.tellg() << " p " << os.tellp() << std::endl;
}
the output I get when it works
g 0 p 0
g 0 p 7
the output I get on visual studio 2015
g 0 p 0
g -1 p -1
any ides?
thanks
std::sstream::setbuf may do nothing:
If s is a null pointer and n is zero, this function has no effect.
Otherwise, the effect is implementation-defined: some implementations do nothing, while some implementations clear the std::string member currently used as the buffer and begin using the user-supplied character array of size n, whose first element is pointed to by s, as the buffer and the input/output character sequence.
You are better off using the std::stringstream constructor to set the data or call str():
#include <sstream>
#include <iostream>
int main()
{
std::string str( 30, '-' );
std::stringstream os;
std::cout << "g " << os.tellg() << " p " << os.tellp() << std::endl;
os.str( str );
os.seekp(7);
std::cout << "g " << os.tellg() << " p " << os.tellp() << std::endl;
}
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
I am just playing around to see where my current understanding of C++ behaviour ends. I wrote the following code, and got some very unexpected results.
#include <iostream>
#include <cstddef>
using namespace std;
int main()
{
const char c = 'A';
cout << c << endl;
size_t l = (size_t)(&c);
char* d = (char*)l;
*d = 'B';
cout << (size_t)d << " " << (size_t)&c << endl;
cout << *d << " " << c << endl;
}
The first line outputs 'A', as expected. On the second line, the two addresses are the same. However, the third line outputs "B A".
Obviously this is terrible code, but why didn't the value of c change (or why didn't it fail to compile?) In other words, if they both have the same address, why don't they have the same value?
My system is GCC 4.8.1 64-bit on MS Windows 7, x86, if it matters.