strange behaviour of cout << Boost::posix_time - c++

I want to calculate time of a loop that it takes to finish.
I do something like:
ptime before = second_clock::local_time(); //get current time
cout << "Started: "<< before << " ... processing ...";
while(foo) {
....
}
ptime after = second_clock::local_time(); // get Current time
cout << "Processing took" << after - before;
This will output: Started: "some time"
then I wait for the loop to finish before I get to see " ... processing ..."
Why is that? It should first cout the whole text and then go into the loop.
If I change the first cout to:
cout << "Started: "<< before;
It doesn't even show me the time before the loop finishes.
That's the most weird thing I've ever seen...seems there's something going wrong with my understanding of boost time.
I'm using boost::threads too in my code but workers are spwaned within the loop so I don't see how this could have to do with this problem.
Can someone help me out here?

ostreams including cout use buffers, which means the implementation can wait to see if you will send more data before actually acting on it.
To get cout to print sooner, use
std::cout << std::flush;
or use std::endl, which is equivalent to "\n" followed by std::flush.

Related

cout is not working inside switch statement

Good day,
I have a loop that computes values and displays the output to the console. However, when I run the code, cout << does not display the output I expected. In fact, it doesn't display any output. The only way I know the code even works is that the values are changing.
cout << was working just fine until I used the switch statement. Every piece of text that I expected to print to the console inside the statement and the loop was just dead text. It didn't work. I also tried flushing the stream using cout.flush. That did not work either I cannot include all of my code, but here are the problem lines:
if (exampleloop == '1'){
ExampleValue = (ExampleValue - 1);
ExampleValue = (ExampleValue - ExampleValue);
cout << "ExampleText " << ExampleValue << " ExampleText";
if (ExampleValue <= 0){
cout << "ExampleText.";
}
if (ExampleValue <= 0){
cout << ExampleText";
}
example_label:
ExampleValue = (ExampleValue1 - ExampleValue1);
cout << "ExampleText! " << ExampleValue! << " ExampleText!";
goto Example_label;
}
And the only way I know that the code is being computed
cout << "EXAMPLE TEXT ExampleValue1 at "<< ExampleValue <<" . ExampleText";
In this case, "Example Text" would never appear on the console. However, the "Example Values" would be computed and the changes would reflect on the code above.
My IDE is repl.it
Is this my fault, or my IDE's? And what is going on?
(Yes, I #include iostream and I'm using namespace std)

Postpone standard output in the end

Many warning messages (via std::cout) might be printed out during the process. Is there a way to postpone the printing of the warning messaged in the end of the program? There are huge amount of the processing information will be printed. I'm planing to have all the warnings together in the end rather than scattered around.
More background:
code is already there.
there are about 50 warning messages within the code (in case if there is some sort of delay( ) function, I don't want to add 50 times, would be nice if there is an globally delaye/postpone function for stand output)
Thanks
One way to do it is to send everything to a stringstream, and then print at the end.
For example:
#include <iostream>
#include <sstream>
int main(){
int i = 5, j = 4;
std::stringstream ss;
std::cout << i * j << std::endl;
ss << "success" << std::endl;
std::cout << j + i * i + j << std::endl;
ss << "failure" << std::endl;
std::cout << ss.str() << std::endl;
return 0;
}
Output:
20
33
success
failure
If you're just trying to delay all printing of std::cout what you can do is redirect standard out to a string stream that acts as a buffer. It's pretty simple and avoids all of the dup, dup2, and piping stuff that one might be inclined to try.
#include <sstream>
// Make a buffer for all of your output
std::stringstream buffer;
// Copy std::cout since we're going to replace it temporarily
std::streambuf normal_cout = std::cout.rdbuf();
// Replace std::cout with your bufffer
std::cout.rdbuf(buffer.rdbuf());
// Now your program runs and does its thing writing to std::cout
std::cout << "Additional errors or details" << std::endl;
// Now restore std::cout
std::cout.rdbuf(normal_cout);
// Print the stuff you buffered
std::cout << buffer.str() << std::endl;
Also in the future, you should really use a buffer for errors from the start OR at a minimum write errors and logging to std::cerr so that your normal runtime print outs aren't cluttered with errors.

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.

missing cout before segmentation fault

I had a segmentation fault in my code, so I put many cout on the suspicious method to localise where.
bool WybierajacyRobot::ustalPoczatekSortowania(){
cout << "ustal poczatek sortowania: " << poczatekSortowania << endl ;
list< Pojemnik >::iterator tmp;
cout << "LOL"; // <-- this cout doesn't print when segfault
if (!poczatekSortowania){ // <- T1
cout << "first task" ;
tmp = polka.begin();
}
else{ // <-- T2
cout << " second task " ;// <-- this cout doesn't print when segfault
tmp = ostatnioUlozony;
cout << " debug cout " ; // <-- this cout doesn't print when segfault
++tmp; // <-- segfault
} ...
If the method was call and don't have segfault every cout from T1 and before was printed.
In line ++tmp is segfault because ostatnioUlozony is NULL, when method go to T2 every cout without first wasn't printed. Why?
I'm using Netbeans ang gcc, I found the "segfault line" with debug in Netbeans, but before I use then I spend some time on adding cout line and running program.
Thanks a lot,
You need to flush the output stream with either std::flush or std::endl (which will give a newline as well), otherwise you are not guaranteed to see the output:
cout << " second task " << std::flush;
Nonetheless, you have undefined behaviour if you increment a singular iterator (which the null pointer is), so this is only likely to work. As far as C++ is concerned, your program could launch a nuclear missile instead.
Another solution is to use std::cerr instead of std::cout. It is unbuffered, so no flushing is required, and it's slightly more idiomatic to use std::cerr for debugging purposes.

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!