Printing addresses with 0x notation - c++

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.

Related

Is there an easy way to print an int without removing leading zeros? [duplicate]

How can I format my output in C++? In other words, what is the C++ equivalent to the use of printf like this:
printf("%05d", zipCode);
I know I could just use printf in C++, but I would prefer the output operator <<.
Would you just use the following?
std::cout << "ZIP code: " << sprintf("%05d", zipCode) << std::endl;
This will do the trick, at least for non-negative numbers(a) such as the ZIP codes(b) mentioned in your question.
#include <iostream>
#include <iomanip>
using namespace std;
cout << setw(5) << setfill('0') << zipCode << endl;
// or use this if you don't like 'using namespace std;'
std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;
The most common IO manipulators that control padding are:
std::setw(width) sets the width of the field.
std::setfill(fillchar) sets the fill character.
std::setiosflags(align) sets the alignment, where align is ios::left or ios::right.
And just on your preference for using <<, I'd strongly suggest you look into the fmt library (see https://github.com/fmtlib/fmt). This has been a great addition to our toolkit for formatting stuff and is much nicer than massively length stream pipelines, allowing you to do things like:
cout << fmt::format("{:05d}", zipCode);
And it's currently being targeted by LEWG toward C++20 as well, meaning it will hopefully be a base part of the language at that point (or almost certainly later if it doesn't quite sneak in).
(a) If you do need to handle negative numbers, you can use std::internal as follows:
cout << internal << setw(5) << setfill('0') << zipCode << endl;
This places the fill character between the sign and the magnitude.
(b) This ("all ZIP codes are non-negative") is an assumption on my part but a reasonably safe one, I'd warrant :-)
Use the setw and setfill calls:
std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;
In C++20 you'll be able to do:
std::cout << std::format("{:05}", zipCode);
In the meantime you can use the {fmt} library, std::format is based on.
Disclaimer: I'm the author of {fmt} and C++20 std::format.
cout << setw(4) << setfill('0') << n << endl;
from:
http://www.fredosaurus.com/notes-cpp/io/omanipulators.html
or,
char t[32];
sprintf_s(t, "%05d", 1);
will output 00001 as the OP already wanted to do
Simple answer but it works!
ostream &operator<<(ostream &os, const Clock &c){
// format the output - if single digit, then needs to be padded with a 0
int hours = c.getHour();
// if hour is 1 digit, then pad with a 0, otherwise just print the hour
(hours < 10) ? os << '0' << hours : os << hours;
return os; // return the stream
}
I'm using a ternary operator but it can be translated into an if/else statement as follows
if(c.hour < 10){
os << '0' << hours;
}
else{
os << hours;
}

C++ printing pointer doesn't acknowledge showbase

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.

Integer to string conversion issues

I am experiencing a few problems with Crypto++'s Integer class. I am using the latest release, 5.6.2.
I'm attempting to convert Integer to string with the following code:
CryptoPP::Integer i("12345678900987654321");
std::ostrstream oss;
oss << i;
std::string s(oss.str());
LOGDEBUG(oss.str()); // Pumps log to console and log file
The output appears to have extra garbage data:
12345678900987654321.ÍÍÍÍÍÍÍÍÍÍÍýýýý««««««««îþîþ
I get the same thing when I output directly to the console:
std::cout << "Dec: " << i << std::endl; // Same result
Additionally, I cannot get precision or scientific notation working. The following will output the same results:
std::cout.precision(5); // Does nothing with CryptoPP::Integer
std::cout << "Dec: " << std::setprecision(1) << std::dec << i << std::endl;
std::cout << "Sci: " << std::setprecision(5) << std::scientific << i << std::endl;
On top of all of this, sufficiently large numbers breaks the entire thing.
CryptoPP::Integer i("12345");
// Calculate i^16
for (int x = 0; x < 16; x++)
{
i *= i;
}
std::cout << i << std::endl; // Will never finish
Ultimately I'm trying to get something where I can work with large Integer numbers, and can output a string in scientific notation. I have no problems with extracting the Integer library or modifying it as necessary, but I would prefer working with stable code.
Am I doing something wrong, or is there a way that I can get this working correctly?
I'm attempting to convert Integer to string with the following code:
CryptoPP::Integer i("12345678900987654321");
std::ostrstream oss;
oss << i;
std::string s(oss.str());
LOGDEBUG(oss.str()); // Pumps log to console and log file
The output appears to have extra garbage data:
12345678900987654321.ÍÍÍÍÍÍÍÍÍÍÍýýýý««««««««îþîþ
I can't reproduce this with Crypto++ 5.6.2 on Visual Studio 2010. The corrupted output is likely the result of some other issue, not a bug in Crypto++. If you haven't done so already, I'd suggest trying to reproduce this in a minimal program just using CryptoPP::Integer and std::cout, and none of your other application code, to eliminate all other possible problems. If it's not working in a trivial stand-alone test (which would be surprising), there could be problems with the way the library was built (e.g. maybe it was built with a different C++ runtime or compiler version from what your application is using). If your stand-alone test passes, you can add in other string operations, logging code etc. until you find the culprit.
I do notice though that you're using std::ostrstream which is deprecated. You may want to use std::ostringstream instead. This Stack Overflow answer to the question "Why was std::strstream deprecated?" may be of interest, and it may even the case that the issues mentioned in that answer are causing your problems here.
Additionally, I cannot get precision or scientific notation working.
The following will output the same results:
std::cout.precision(5); // Does nothing with CryptoPP::Integer
std::cout << "Dec: " << std::setprecision(1) << std::dec << i << std::endl;
std::cout << "Sci: " << std::setprecision(5) << std::scientific << i << std::endl;
std::setprecision and std::scientific modify floating-point input/output. So, with regular integer types in C++ like int or long long this wouldn't work either (but I can see that especially with arbitrary-length integers like CryptoPP:Integer being able to output in scientific notation with a specified precision would make sense).
Even if C++ didn't define it like this, Crypto++'s implementation would still need to heed those flags. From looking at the Crypto++ implementation of std::ostream& operator<<(std::ostream& out, const Integer &a), I can see that the only iostream flags it recognizes are std::ios::oct and std::ios::hex (for octal and hex format numbers respectively).
If you want scientific notation, you'll have to format the output yourself (or use a different library).
On top of all of this, sufficiently large numbers breaks the entire
thing.
CryptoPP::Integer i("12345");
// Calculate i^16
for (int x = 0; x < 16; x++)
{
i *= i;
}
std::cout << i << std::endl; // Will never finish
That will actually calculate i^(2^16) = i^65536, not i^16, because on each loop you're multiplying i with its new intermediate value, not with its original value. The actual result with this code would be 268,140 digits long, so I expect it's just taking Crypto++ a long time to produce that output.
Here is the code adjusted to produce the correct result:
CryptoPP::Integer i("12345");
CryptoPP::Integer i_to_16(1);
// Calculate i^16
for (int x = 0; x < 16; x++)
{
i_to_16 *= i;
}
std::cout << i_to_16 << std::endl;
LOGDEBUG(oss.str()); // Pumps log to console and log file
The output appears to have extra garbage data:
12345678900987654321.ÍÍÍÍÍÍÍÍÍÍÍýýýý««««««««îþîþ
I suspect what you presented is slighty simplified from what you are doing in real life. I believe the problem is related to LOGDEBUG and the ostringstream. And I believe you are outputting char*'s, and not string's (though we have not seen the code for your loggers).
The std::string returned from oss.str() is temporary. So this:
LOGDEBUG(oss.str());
Is slighty different than this:
string t(oss.str());
LOGDEBUG(t);
You should always make a copy of the string in an ostringstream when you intend to use it. Or ensure the use is contained in one statement.
The best way I've found is to have:
// Note: reference, and the char* is used in one statement
void LOGDEBUG(const ostringstream& oss) {
cout << oss.str().c_str() << endl;
}
Or
// Note: copy of the string below
void LOGDEBUG(string str) {
cout << str.c_str() << endl;
}
You can't even do this (this one bit me in production):
const char* msg = oss.str().c_str();
cout << msg << endl;
You can't do it because the string returned from oss.str() is temporary. So the char* is junk after the statement executes.
Here's how you fix it:
const string t(oss.str());
const char* msg = t.c_str();
cout << msg << endl;
If you run Valgrind on your program, then you will probably get what should seem to be unexplained findings related to your use of ostringstream and strings.
Here is a similar logging problem: stringstream temporary ostream return problem. Also see Turning temporary stringstream to c_str() in single statement. And here was the one I experienced: Memory Error with std:ostringstream and -std=c++11?
As Matt pointed out in the comment below, you should be using an ostringstream, and not an ostrstream. ostrstream has been deprecated since C++98, and you should have gotten a warning when using it.
So use this instead:
#include <sstream>
...
std::ostringstream oss;
...
But I believe the root of the problem is the way you are using the std::string in the LOGDEBUG function or macro.
Your other questions related to Integer were handled in Softwariness's answer and related comments. So I won't rehash them again.

cout no output but printf does

I'm very new to programming in C++ but I'm trying to write some code which filters a specific word from a string and then takes a specific action. For some reason the code does not see the text inside the string.
printf("%s \n", data.c_str());
cout << data;
This shows absolutely nothing - meaning I cannot use .find or write it to a file.
printf("%s \n", data);
This shows exactly what I need.
I am writing the code into data with assembly:
mov data, EDX
Why is that I can only use the the last method?
Edit:
Data is initiated as:
std::string data;
If a pointer to a string is null all subsequent calls to cout
stop working
const char* s=0;
cout << "shown on cout\n";
cout << "not shown" << s << "not shown either\n";
cout << "by bye cout, not shown\n";
The two function calls are not equivalent, as \n at printf flushes the stream. Try with:
cout << data << endl;
Be sure you used
#include <string>
in your file header. With this in place you should be able to use
std::cout << data << endl;
with no issues. If you're using a global namespace for std you may not need the std::, but I'd put it anyway to help you debug a it faster and eliminate that as a possible problem.
In Short
You will have a problem with cout, if you don't put a linebreak at it's end!
In Detail
Try adding an endl to your cout (e.g. std::cout << data << std::endl), or use following instruction to activate "immediate output" for cout (without it needing a linebreak first).
std::cout << std::unitbuf;
Complete example:
std::cout << std::unitbuf;
std::cout << data;
// ... a lot of code later ...
std::cout << "it still works";
Sidenote: this has to do with output buffering, as the name unitbuf suggests (if you want to look up what is really happening here).
This way it is also possible to rewrite the current line, which is a good example, where you would need this ;-)
Practical example
using namespace std;
cout << "I'm about to calculate some great stuff!" << endl;
cout << unitbuf;
for (int x=0; x<=100; x++)
{
cout << "\r" << x << " percent finished!";
// Calculate great stuff here
// ...
sleep(100); // or just pretend, and rest a little ;-)
}
cout << endl << "Finished calculating awesome stuff!" << endl;
Remarks:
\r (carriage return) puts the curser to the first position of the line (without linebreaking)
If you write shorter text in a previously written line, make sure you overwrite it with space chars at the end
Output somewhere in the process:
I'm about to calculate some great stuff!
45 percent finished!
.. and some time later:
I'm about to calculate some great stuff!
100 percent finished!
Finished calculating awesome stuff!

"Roll-Back" or Undo Any Manipulators Applied To A Stream Without Knowing What The Manipulators Were [duplicate]

This question already has answers here:
Restore the state of std::cout after manipulating it
(9 answers)
Closed 4 years ago.
If I apply an arbitrary number of manipulators to a stream, is there a way to undo the application of those manipulators in a generic way?
For example, consider the following:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << "Hello" << hex << 42 << "\n";
// now i want to "roll-back" cout to whatever state it was in
// before the code above, *without* having to know
// what modifiers I added to it
// ... MAGIC HAPPENS! ...
cout << "This should not be in hex: " << 42 << "\n";
}
Suppose I want to add code at MAGIC HAPPENS that will revert the state of the stream manipulators to whatever it was before I did cout << hex. But I don't know what manipulators I added. How can I accomplish this?
In other words, I'd like to be able to write something like this (psudocode/fantasy code):
std::something old_state = cout.current_manip_state();
cout << hex;
cout.restore_manip_state(old_state);
Is this possible?
EDIT:
In case you're curious, I'm interested in doing this in a custom operator<<() I'm writing for a complex type. The type is a kind of discriminated union, and different value types will have different manips applied to the stream.
EDIT2:
Restriction: I cannot use Boost or any other 3rd party libraries. Solution must be in standard C++.
Yes.
You can save the state and restore it:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
std::ios state(NULL);
state.copyfmt(std::cout);
cout << "Hello" << hex << 42 << "\n";
// now i want to "roll-back" cout to whatever state it was in
// before the code above, *without* having to know what modifiers I added to it
// ... MAGIC HAPPENS! ...
std::cout.copyfmt(state);
cout << "This should not be in hex: " << 42 << "\n";
}
If you want to get back to the default state you don't even need to save the state you can extract it from a temporary object.
std::cout.copyfmt(std::ios(NULL));
The standard manipulators all manipulate a stream's format flags, precision and width settings. The width setting is reset by most formatted output operations anyway. These can all be retrieved like this:
std::ios_base::fmtflags saveflags = std::cout.flags();
std::streamsize prec = std::cout.precision();
std::streamsize width = std::cout.width();
and restored:
std::cout.flags( saveflags );
std::cout.precision( prec );
std::cout.width( width );
Turning this into an RAII class is an exercise for the reader...
Saving and restoring state is not exception-safe. I would propose to shuffle everything into a stringstream, and finally you put that on the real stream (which has never changed its flags at all).
#include <iostream>
#include <iomanip>
#include <sstream>
int main()
{
std::ostringstream out;
out << "Hello" << std::hex << 42 << "\n";
std::cout << out.str();
// no magic necessary!
std::cout << "This should not be in hex: " << 42 << "\n";
}
Of course this is a little less performant. The perfect solutions depends on your specific needs.
Boost IO State saver might be of help.
http://www.boost.org/doc/libs/1_40_0/libs/io/doc/ios_state.html
I know that is an old question, but for future generations:
You can also write a simple state saver yourself (it will certainly help you avoid leaving the state changed). Just use the solution suggested by #loki and run it from the constructor/destructor of an object (in short: RAII) along these lines:
class stateSaver
{
public:
stateSaver(ostream& os): stream_(os), state_(nullptr) { state_.copyfmt(os); }
~stateSaver() { stream_.copyfmt(state_); }
private:
std::ios state_;
ostream& stream_;
};
Then, you will use it like this:
void myFunc() {
stateSaver state(cout);
cout << hex << 42 << endl; // will be in hex
}
int main() {
cout << 42 << endl; // will be in dec
myFunc();
cout << 42 << endl; // will also be in dec
}