ofstream output string/charactor and not doubles - c++

I have some C++ code developed by a former employee.
I'm trying to clarify/test some of the software results.
In an intermediate step, the software saves a 'binary' dat file with results, which is later imported by another part of the software.
My aim is to change this output from 'binary' to human readable numbers.
The output file is defined:
ofstream pricingOutputFile;
double *outputMatrix[MarketCurves::maxAreaNr];
ofstream outputFile[MarketCurves::maxAreaNr];
The write step is this one:
pricingOutputFile.write((char *)&outputMatrix[area], sizeof(double));
The matrix is filled with 'doubles'
Is there a way to change this to output a human readable file?
I have tried various std::string cout and other methods 'googled' but until now without success.
Tried the suggestion with << but that gave the following error:
error C2297: '<<' : illegal, right operand has type 'double'
The sugestions her pushed me on the right track:
sprintf_s(buffer, 10, "%-8.2f", rowPos);
pricingOutputFile.write((char *)&buffer, 10);
Inspiration found at:
http://www.tenouk.com/cpluscodesnippet/usingsprintf_s.html
Thanks for the help

In this code memory occupied by a double is dumped into a file
pricingOutputFile.write((char *)&outputMatrix[area], sizeof(double));
To produce human readable you need to use overloaded operator << :
pricingOutputFile << outputMatrix[area];

You can just inline this:
pricingOutputFile << std::fixed
<< std::setw(11)
<< std::setprecision(6)
<< std::setfill('0')
<< rowMin;
But that is very imperative. I always like to stay declarative as long as possible. One simple way to do this would be:
void StreamPriceToFile(ofstream & output, const double & price) const
{
output << std::fixed
<< std::setw(11)
<< std::setprecision(6)
<< std::setfill('0')
<< price;
}
//wherever used
StreamPriceToFile(pricingOutputFile, rowMin);
But even better (in my opinion) would be something like:
//setup stream to receive a price
inline ios_base& PriceFormat(ios_base& io)
{
io.fixed(...);
...
}
//wherever used
pricingOutputFile << PriceFormat << rowMin;
My C++ is very rusty or I'd fill in PriceFormat.

The sugestions her pushed me on the right track:
sprintf_s(buffer, 10, "%-8.2f", rowPos);
pricingOutputFile.write((char *)&buffer, 10);
Inspiration found at: http://www.tenouk.com/cpluscodesnippet/usingsprintf_s.html

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;
}

Why std:: setw and std::hex not appropriate of code below?

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.

Switching to cout from printf - Complex format specifier patterns

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.

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!