Taking Query And Flushing in C++

Can anyone tell me how to make query and flush the output in C++.

I haven’t done this before.

So , please kindly answer my question.

Thank’s

:slight_smile:

1 Like

There are great blogs on flushing and interactive problems here and here.
Hope it helps :slight_smile:

What does buffer flush means in C++ ?
A buffer flush is the transfer of computer data from a temporary storage area to the computer’s permanent memory. For instance if we make any changes in a file, the changes we see on one computer screen are stored temporarily in a buffer.
Usually a temporary file come into existence when we open any word document, and automatically destroyed when we close our main file. Thus when we save our work, the changes that we’ve made to our document since the last time we saved it are flushed from the buffer to permanent storage on the hard disk.

In C++, we can explicitly flushed to forced the buffer to be written. Generally std::endl function works the same by inserting new-line character and flushes the stream. stdout/cout is line-buffered that is the output doesn’t get sent to the OS until you write a newline or explicitly flush the buffer. For instance,

// Causes only one write to underlying file
// instead of 5, which is much better for
// performance.
std::cout << a << " + " << b << " = " << std::endl;

But there is certain disadvantage something like,

// Below is C++ program
#include
#include
#include

using namespace std;

int main()
{
for (int i = 1; i <= 5; ++i)
{
cout << i << " ";
this_thread::sleep_for(chrono::seconds(1));
}
cout << endl;
return 0;
}

The above program will output 1 2 3 4 5 at once.
Therefore in such cases additional “flush” function is used to ensure that the output gets displayed according to our requirement. For instance,

filter_none
brightness_4
// C++ program to demonstrate the
// use of flush function
#include
#include
#include
using namespace std;
int main()
{
for (int i = 1; i <= 5; ++i)
{
cout << i << " " << flush;
this_thread::sleep_for(chrono::seconds(1));
}
return 0;
}
The above program will program will print the
numbers(1 2 3 4 5) one by one rather than once.
The reason is flush function flushed the output
to the file/terminal instantly.
Note:

You can’t run the program on online compiler to see the difference, since they give output only when it terminates. Hence you need to run all above programs in offline complier like gcc or clang.
Reading cin flushes cout so we don’t need an explicit flush to do this.
References:

1 Like

Is taking query is just cout in c++?

I think you mean ‘cin’. Yes, taking a query in interactive problems is just like taking queries in a normal problem, but you can only take one query as input at a time. Only after you provide some output to that query, the judge gives you another query depending on your output.