Issue with C++ console output - c++

#include <iostream>
using namespace std;
int main()
{
cout << 1;
while (true);
return 0;
}
I thought that this program should print 1 and then hung. But it doesn't print anything, it just hungs.
cout << endl or cout.flush() can solve this problem, but I still want to know why it's not working as expected :)
This problem appeared during codeforces contest and I spent a lot of time on looking at strange behavior of my program. It was incorrect, it also hunged, hidden output was actually debug information.
I tried using printf (compiling with gcc) and it behaves as well as cout, so this question can be referred to C also.

You writing to a buffer. You need to flush the buffer. As #Guvante mentioned, use cout.flush() or fflush(stdout) for printf.
Update:
Looks like fflush actually works with cout. But don't do that - it may not be the fact in all cases.

That is because cout buffers output. You have to flush the buffer for it to actually print.
endl and flush() both perform this flushing.
Also note that your program hangs because you have an infinite loop (while(true);).
The reason it does this is so that if you are printing a lot of data (say 1000 numbers) it can do so drastically more efficiently. Additionally most minor data points end with endl anyway, since you want your output to span multiple lines.

Concerning printf, the same as cout holds: you're printing into a buffer, you need to flush it with fflush(stdout);. Termination will flush the buffer, this is why you can see the output without your infinite loop.
See Why does printf not flush after the call unless a newline is in the format string? for more information.

Related

why we need to close a file to complete the writing process of a file? [duplicate]

I understand cout << '\n' is preferred over cout << endl; but cout << '\n' doesn't flush the output stream. When should the output stream be flushed and when is it an issue?
What exactly is flushing?
Flushing forces an output stream to write any buffered characters. Read streamed input/output.
It depends on your application, in real-time or interactive applications you need to flush them immediately but in many cases you can wait until closing the file and leave the program to flush it automatically.
When must the output stream in C++ be flushed?
When you want to be sure that data written to it is visible to other programs or (in the case of file streams) to other streams reading the same file which aren't tied to this one; and when you want to be certain that the output is written even if the program terminates abnormally.
So you would want to do this when printing a message before a lengthy computation, or for printing a message to indicate that something's wrong (although you'd usually use cerr for that, which is automatically flushed after each output).
There's usually no need to flush cerr (which, by default, has its unitbuf flag set to flush after each output), or to flush cout before reading from cin (these streams are tied so that cout is flushed automatically before reading cin).
If the purpose of your program is to produce large amounts of output, either to cout or to a file, then don't flush after each line - that could slow it down significantly.
What exactly is flushing?
Output streams contain memory buffers, which are typically much faster to write to than the underlying output. Output operations put data into the buffer; flushing sends it to the final output.
First, you read wrong. Whether you use std::endl or '\n'
depends largely on context, but when in doubt, std::endl is
the normal default. Using '\n' is reserved to cases where
you know in advance that the flush isn't necessary, and that it
will be too costly.
Flushing is involved with buffering. When you write to
a stream, (typically) the data isn't written immediately to the
system; it is simply copied into a buffer, which will be written
when it is full, or when the file is closed. Or when it is
explicitly flushed. This is for performance reasons: a system
call is often a fairly expensive operation, and it's generally
not a good idea to do it for every characters. Historically,
C had something called line buffered mode, which flushed with
every '\n', and it turns out that this is a good compromize
for most things. For various technical reasons, C++ doesn't
have it; using std::endl is C++'s way of achieving the same
results.
My recommendation would be to just use std::endl until you
start having performance problems. If nothing else, it makes
debugging simpler. If you want to go further, it makes sense to
use '\n' when you're outputting a series of lines in just
a few statements. And there are special cases, like logging,
where you may want to explicitly control the flushing.
Flushing can be disastrous if you are writing a large file with frequent spaces.
For example
for(int i = 0 ;i < LARGENUMBER;i++)
{//Slow?
auto point = xyz[i];
cout<< point.x <<",",point.y<<endl;
}
vs
for(int i = 0 ;i < LARGENUMBER;i++)
{//faster
auto point = xyz[i];
cout<< point.x <<",",point.y<<"\n";
}
vs
for(int i = 0 ;i < LARGENUMBER;i++)
{//fastest?
auto point = xyz[i];
printf("%i,%i\n",point.x,point.y);
}
endl() was often know for doing other things, for example synchronize threads when in a so-called debug mode on MSVC, resulting in multithreaded programs that, contrary to expectation, printed uninterrupted phrases from different threads.
I/O libraries buffer data sent to stream for performance reasons. Whenever you need to be sure data has actually been sent to stream, you need to flush it (otherwise it may still be in buffer and not visible on screen or in file).
Some operations automatically flush streams, but you can also explicitly call something like ostream::flush.
You need to be sure data is flushed, whenever for example you have other program waiting for the input from first program.
It depends on what you are doing. For example, if you are using the console to warn the user about a long process... printing a series of dots in the same line... flushing can be interesting. For normal output, line per line, you should not care about flushing.
So, for char based output or non line based console output, flushing can be necessary. For line based output, it works as expected.
This other answer can clarify your question, based on why avoiding endl and flushing manually may be good for performance reasons:
mixing cout and printf for faster output
Regarding what is flushing: when you write to a buffered stream, like ostream, you don't have any guarantee that your data arrived the destination device (console, file, etc). This happens because the stream can use intermediary buffers to hold your data and to not stop your program. Usually, if your buffers are big enough, they will hold all data and won't stop your program due to slow I/O device. You may have already noticed that the console is very slow. The flush operation tells the stream that you want to be sure all intermediary data arrived on the destination device, or at least that their buffers are now empty. It is very important for log files, for example, where you want to be sure (not 100%) a line will be on disk not in an buffer somewhere. This becomes more important if your program can't loose data, i.e., if it crashes, you want to be sure you did you best to write your data on disk. For other applications, performance is more important and you can let the OS decide when to flush buffers for you or wait until you close the stream, for example.

Speeding printf and cout in windows

Windows cout and printf is really slow, so when a lot of data is sent it slows applications (it happens with code running during days to check if all is working well).
A metod to make it faster is to use a buffer by writting following code at the beginning of the main() function:
#ifndef __linux__ //Introduce this code at the beginning of main() to increase a lot the speed of cout in windows:
char buffer_setvbuf[1024];setvbuf(stdout, buffer_setvbuf, _IOFBF, sizeof buffer_setvbuf); //¿¡¡Sometimes it does not print cout inside a function until cout is used in main() or end of buffer is reached.
#endif
But unfortunately a side effect is that sometimes it does not print the data because the buffer is not full.
Then the questions:
1. How to force print: by making \n?
2. How to disable the buffer?
printf
I see you are trying to use larger buffer on memory to reduce the number of writes on stdout. Indeed, your code would not print anything until your buffer becomes full, because the buffering mode is set to _IOFBF (i.e. full buffering). Since you want control when to flush, there are two ways to go about.
Use _IOLBF (i.e. line buffering), and put newline character whenever you want to flush.
Call fflush(stdout) to manually flush the buffer.
std::cout
I think std::cout should be preferred when writing c++ code, because of its ease of use. One thing that might slow down the I/O process is synchronization between iostream and stdio. As far as I know, the default on many systems is to keep the two in sync, and it has some overhead. You can disable it by calling std::ios_base::sync_with_stdio(false). reference
When you need to flush output, you can use what is called "manipulators" for output stream - namely std::flush and std::endl. When those manipulators are put into an output stream like the following: std::cout << "your string" << std::endl, it is guaranteed that the output stream is flushed.
std::endl reference
std::flush reference
Bottom Line
Use fflush to flush stdout when using printf for output.
I recommend trying std::cout with sync off, and test if it fits your performance need.

cin statement will not compile

Alright, I have a programming challenge due but unfortunately, although my code does in theory, doesn't work so I was wondering if it was a compiler issue (I use Code::Blocks) or if its something I'm not seeing. Any help would be appreciated, Thanks!
Here's my code:
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
int main(){
double sliceStore, sliceSize = 14.125, totalSlice, area;
cout << "How Many Slices?" << endl;
//getline(cin,sliceStore);
cin >> sliceStore >> endl;
return 0;
}
Remove "endl" from the input statement !!
The complete error message for this is not nice and goes on for a few pages, but code::blocks usually fronts GCC and g++, GCC's C++ compiler, should have started the message of with something like this:
cin >> sliceStore >> endl;
^
In English, the compiler could not find a way for the >> operator to put data into endl. A bit of reading up on what endl is may have solved your problem. endl is a function, not a variable.
ostream& endl(ostream&)
Crack your textbook and read up on input and output streams.
cin is the name of an input stream attached to the main console, usually represented by the command prompt. Input streams use >>, which is also a function, one that usually looks like
istream& operator>>(istream&, somedatatype&)
So cin >> endl; really looks like is a function call something like
cin = operator>>(cin, endl());
However, no one has built an operator>> with a somedatatype that looks like ostream& endl(ostream&) and the compiler prints out a huge list of operator>> possibilities that look something like it as a hint of what you might have meant to do.
Most of the time this is helpful. Most functions only have a couple overloads, and you can quickly see what you did wrong. But operator>> has an overload for every common datatype and dozens of not so common data types. Blah.
Onto what the endl function does.
It tells an output stream to do two things: to end the line and to flush the output buffer.
Ending the line's pretty simple, the only caveat is everybody seems to do it differently so if you compile the same program under different operating systems you'll get slightly different output.
The output buffer flush is a instruction to the output stream to send any data it's been holding onto, buffering, for a good chance to send it.You generally want to send stuff in chunks because it's more efficient. Say you want to write to a file. In the world of a computer where things happen in nanoseconds, writing to a file can take seconds. For example, the hard disk could be in a low power sleep state and have to start spinning. Then it has to find where the file goes on the hard drive. Then it has to wait for the hard drive to spin into the right position. You don't want to go through all that just to write one character as each time you press a key on the keyboard, so the computer builds up a bunch of writes in memory--the buffer--thee writes the contents of the buffer after it fills up, hasn't been added to for a while, or is forced to with a flush instruction. endl provides that flush. As a result, overuse of endl can slow down your program.

integer producing hex values error

something weird is happening to my program. I am currently using lots of threads in my program, and will not be feasible to paste everything here.
However this is my problem:
int value = 1000;
std::cout << value << std::endl;
//output: 3e8
Any idea why is my output 3e8?
Whats the command to fix it back to print decimal values?
Thanks in advance! :)
Some other thread changed the default output radix of the std::cout stream to hexadecimal. Note that 100010 = 3e816, i.e. 1000 == 0x3e8.
Somewhere in your program a call such as:
std::cout << std::hex << value;
has been used. To revert output to normal (decimal) use:
std::cout << std::dec;
here is a relevent link to the different ways numbers can be output on std::cout.
Also, as pointed out in the comments below, the standard method of modifying cout flags safely appears to be the following:
ios::fmtflags cout_flag_backup(cout.flags()); // store the current cout flags
cout.flags ( ios::hex ); // change the flags to what you want
cout.flags(cout_flag_backup); // restore cout to its original state
Link to IO base flags
As stated in the comments below, it would also be wise to point out that when using IO Streams it is a good idea to have some form of synchronisation between the threads and the streams, that is, make sure no two threads can use the same stream at one time.
Doing this will probably also centralise your stream calls, meaning that it will be far easier to debug something such as this in the future.
Heres an SO question that may help you
Chances are that another thread has changed the output to hex on cout. I doubt that these streams are thread-safe.

C++ microkernel cout problem

Ok, I'm working on my Operating Systems assignment. I need to write a microkernel which is able to do some basic stuff with threads, semaphores, events, etc.
BCC 3.1 is imitating my system environment. Classical debugging is really not of use. I'm debugging in cout style.
Problem is weird behavior of cout. It writes out in blocks or something. If I do, like, 40 couts it writes everything out. If I do 39 of them, it doesn't write any of them. On other hand if i do between 40 and 79 couts, it still writes only first 40, but if I do 80 of them, they're all ok, etc. Numbers are not exact, I'm not sure what's the number really. But I have also noticed that changing the length of string that is cout-ed effects the same way. Only I don't know how many characters equals one cout call.
Additional information available upon request. Thanks in forward.
sounds like buffering regardless of the fact std::cout shouldn't buffer output. in any case you can try flushing cout by
std::cout.flush();
or
std::cout << std::flush;
or
std::cout << std::endl;
or even by disabling buffering:
std::cout.rdbuf()->pubsetbuf(0, 0);