I have to rewrite a logging system in C++ as part of project requirements (everything has to be C++ instead of C now), and there are a number of ways in which we log things like mathematical data and pointer addresses. It is fairly common to see a log like:
log("%3.4f %d %zp %5.8f", ...);
In C++, using cout instead of printf, it seems a bit more of an involved process to setup such a logging format, eg, taking the following snippet from C++ Primer Plus (Prata):
ios_base::fmtflags initial;
initial = os.setf(ios_base::fixed); // save initial formatting state
os.precision(0);
os.setf(ios::showpoint);
os.precision(1);
os.width(12);
This looks like it will set the width and precision for all floating point items in the argument list, and won't allow me to have different values for different variables.
Can cout even generate such a string in a simple manner with just one line of code, or should I use sprintf to prepare my strings and then feed them to cout?
Thanks!
Question the requirements!
printf works fine in C++, proper use of compiler warnings prevent type inconsistencies. The C++ formatting alternative is too complicated and error prone: it is so easy to leave the stream formatting in a different state than upon entry.
If you really need to use cout, use snprintf() to format the log entry and shift the formatted string to cout.
Can cout even generate such a string in a simple manner with just one
line of code, or should I use sprintf to prepare my strings and then
feed them to cout?
I agree that sprintf() is not C++. It merely provides some manner of backward compatibility ... i.e. it has been provided specifically so that you can post-pone the conversion (of c to c++) and that technical debt to later in your schedule.
Here is a code sample from when I 'fixed' a log to be C++. (I left in the sprintf() to help document the new C++ code.)
//retVal = ::sprintf(buff1, "%08llx %2d:%02d:%02d, %05llu.%03llu: ",
// a_pid, hr, min, sec, (ms_of_day / 1000), (rt_ms % 1000));
// use stringstream formatting, not sprintf
buff1 << std::dec << std::setfill('0') << std::setw(8) << a_pid << " "
<< std::setfill('0') << std::setw(2) << hr << ":"
<< std::setfill('0') << std::setw(2) << min << ":"
<< std::setfill('0') << std::setw(2) << sec << ", "
<< std::setfill('0') << std::setw(5) << (ms_of_day / 1000)
<< "."
<< std::setfill('0') << std::setw(3) << (ms_of_day % 1000)
<< ": ";
I only had to do this once.
In a lot of ways, I do not miss the 'unsafe-type' style of sprintf.
If there is something special you do often, you might also consider creating something like the following.
std::string ssprintf0x08x(std::string label, void* ptr)
{
std::stringstream ss;
ss << label << "0x"
<< std::hex << std::internal << std::setw(8)
<< std::setfill('0')
<< reinterpret_cast<uint64_t>(ptr);
return (ss.str());
}
I only had to implement this one time.
Answer to question:
Can cout even generate such a string in a simple manner with just one
line of code?
Yes. Of course.
C++ stream output has a learning curve, but it leads you to a type-safe approach for text output.
And, perhaps you are realizing, one line of code can be quite long.
Related
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;
}
I had been seeing some code snippet from someone as shown below:
before changed:
void pal::type3_message::debug_print(std::ostream & out) const
{
out << "### type3_message:" << '\n'
<< pal::as_hex_dump(as_bytes())
<< "lm_response = " << pal::as_hex_string(lm_response_)
<< "\nnt_response = " << pal::as_hex_string(nt_response_)
<< "\ndomain = " << domain_
<< "\nuser = " << user_
<< "\nworkstation = " << workstation_
<< "\nsession_key = " << pal::as_hex_string(session_key_)
<< std::hex << std::setw(8) << std::setfill('0')
<<"\nssp_flags = " << ssp_flags_;
}
after changed:
std::string pal::type3_message::debug_print() const
{
std::ostringstream buf;
buf << "### type3_message:" << '\n'
<< pal::as_hex_dump(as_bytes())
<< "lm_response = " << pal::as_hex_string(lm_response_)
<< "\nnt_response = " << pal::as_hex_string(nt_response_)
<< "\ndomain = " << domain_
<< "\nuser = " << user_
<< "\nworkstation = " << workstation_
<< "\nsession_key = " << pal::as_hex_string(session_key_)
<< std::hex << std::setw(8) << std::setfill('0')
<<"\nssp_flags = " << ssp_flags_;
return buf.str();
}
I am not very sure of the change above, is anyone can tell me how that should happened and the deep significance of it ? look forward for response and appreciate of it.
I'm not exactly sure what you are asking, so I'm just explaining what the code sample does and what the major difference between both functions is:
void pal::type3_message::debug_print(std::ostream & out) const
This function writes a message to an output stream that is referenced by the out parameter. It has no return value.
std::string pal::type3_message::debug_print() const
This function seems to output the same message but instead of writing it to a stream, it stores the message in a string. This string is returned by the function.
The implementation of both functions looks very similar because the 2nd function uses a temporary std::ostringstream internally. This is a stream that exist in memory only. In contrast, you could pass a file stream like std::ofstream to the 1st function.
Please clarify your question if you want to know more.
can tell me how that should happened and the deep significance of it?
The first method receives an std::ostream& parameter, and streams more than 10 different chunks of text into it.
The second method streams the same 10 chunks of text into a locally created (automatic var) std::ostringstream. This concatenates the chunks prior to returning the string.
Possible usage examples (to achieve same output on std::cout):
pal::type3_message::debug_print(std::cout);
std::cout << std::endl;
and
std::cout << pal::type3_message::debug_print() << std::endl;
I prefer the std::stringstream approach, but I have used both.
In the first method, the thread can be 'interrupted' in more places (between the 10) with possible impact to the not private stream effort. Does this cause an issue? I have not investigate on a desktop.
The second method completes the concatenation, then returns a string. All the previous interruption points are still there, but none affect the delivery to std::cout, a shared stream destination. Note there is still 1 (or maybe 2) interruptions places in this path (to append the string). Still, this is probably less likely to produce visible issues.
In an embedded system I once worked on, because of drivers it had, the second method was clearly better (in terms of thread interruptions during use) and appeared it did not need mutex guard on the out channel.
On Ubuntu, I have added mutex guard's to access std::cout ... to avoid the 'inter-mixed' text, though I did not confirm that the change-described-in-this-post could have been sufficient.
I have an in-ram-log with a round-robin-buffer, and that shared resource has a mutex guard. Never any problems with multiple threads contributing to the same log.
Note: Per the post Question, I see no difference in either stream effort with respect to std::hex or std::setw, both are used identically.
update per July 2, comment
I agree that 'after' is what I prefer.
I do not recognize the phrase "do not mess with borrowed things". I looked and decided Google's report on this phrase had no software relevance.
But it reminded me of a possibly related caution I have heard, "code is like an onion". The guy who repeated this to me (obsessively) resisted 'fixing' things (a crash for example) because, I surmise, he worried that any changes might break 'behaviour' in an undetectable manner. Thus, he worked through 'all the onion layers' until he was sure nothing bad would happen, before he committed a code change. 'Paralysis by analysis' comes to mind.
I am, apparently, much more tolerant to trying something else (and test, test, test...) That crash was easy to fix, and the crash certainly held up progress on understanding the deeper layers of the onion.
Please consider the following:
unsigned char a(65);
unsigned char z(90);
std::cout << std::hex << a << ", " << z <<std::endl;
Output:
A, Z
But desired output is:
41, 5a
To achieve this I'd like to avoid having to convert values like this, say:
std::cout << std::hex << int(a) << ", " << int(z) <<std::endl;
and instead have some magical manipulator that I can include beforehand:
std::cout << uchar_hex_manip << a << ", " << z << std::endl;
So my question is, how can I define 'uchar_hex_manip' to work as required?
UPDATE: I appreciate all the comments and suggestions so far but I have already said I want to avoid converting the values and no-one seems to have acknowledged that fully. The 'a << ", " << z' I mentioned above is representative of the values to be later streamed in - the actual use case of this in our application is that there is something more complex than that going on where for various reasons it is ideal not to have to shoe-horn in some casts for specific cases.
If you want to print char as hex, you will need to convert it to a an int:
std::cout << std::hex << static_cast<int>('a');
should do the trick.
The reason std::hex doesn't work on char (or unsigned char) is that the stream output operator for char is defined to print the character as the output. There is no modifier to change this behaviour (and although #soon suggests to write your own class - that's a lot of work to avoid a cast).
My code:
std::vector<double> thePoint(4);
thePoint[0] = 86;
thePoint[1] = -334.8836574;
thePoint[2] = 24.283;
thePoint[3] = 345.67675;
ofstream file1(tempFileName, ios::trunc);
file1 << std::setprecision(16) << thePoint[0] << " ";
file1 << std::fixed << std::setprecision(2) << thePoint[1] << " ";
file1 << std::setprecision(16) << thePoint[2] << " ";
file1 << std::setprecision(16) << thePoint[3];
I get:
86 -334.88 24.28300000000000 345.6767500000000
I want:
86 -334.88 24.283 345.67675
The odd formatting is needed for an interface with other picky code.
You should do this:
file1 << std::fixed << std::setprecision(2) << thePoint[1] << " ";
file1.unsetf(ios_base::fixed);
file1 << std::setprecision(16) << thePoint[2];
The floatfield format flag can take any of its two possible values (using the manipulators fixed and scientific), or none of them (using ios_base::unsetf).
You can do it by forcing the floatfield to an empty value:
file1.setf( std::ios_base::fmtflags(), std::floatfield );
In practice, it's rare to want to, however. The usual protocol is to
save the format flags, and restore them when you're through:
std::ios_base::fmtflags originalFlags = file1.flags();
// ...
file1.flags( originalFlags );
Of course, you'd normally use RAII to do this in a real program. You
should have a IOSave class in your toolbox which will save the flags,
the precision and the fill character in its constructor, and restore
them in the destructor.
It's also not very good practice to use std::setprection etc.
directly. A better solution would be to define your own manipulators,
with names like pression or volume, and use those. This is logical
markup, and means that you control the format for e.g. pression from one
central location, rather than having it spread throughout the program.
And if you write your own manipulators, it's relatively easy to have
them restore the original formatting parameters at the end of the full
expression. (The manipulator objects will be temporaries, destructed at
the end of the full expression.)
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;