0

im new to programming and was trying to understand buffers and came across : https://www.tutorialspoint.com/what-does-buffer-flush-means-in-cplusplus#:~:text=The%20buffer%20flush%20is%20used,the%20buffer%20to%20be%20written.

it said that if the buffer is not flushed, the numbers will be printed at once while it will be printed one after the other while flushing the buffer.But after trying it on my computer, they both printed one after the other.

idk this might be a silly question

#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
main() {
for (int x = 1; x <= 5; ++x) {
cout << x << " " << flush;
this_thread::sleep_for(chrono::seconds(1)); //wait for 1 second
}
cout << endl;
}
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
main() {
for (int x = 1; x <= 5; ++x) {
cout << x << " ";
this_thread::sleep_for(chrono::seconds(1)); //wait for 1 second
}
cout << endl;
}
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • I'm guessing whatever terminal you are using is unbuffered – Alan Birtles Dec 03 '22 at 09:04
  • The rules regarding buffering are discussed here [What are the rules of automatic stdout buffer flushing in C?](https://stackoverflow.com/q/39536212/3422102) while it pertains to C, the same applies to C++. How are you running your code? From the command line or running the program in an IDE like VS or vscode? – David C. Rankin Dec 03 '22 at 09:15
  • Not flushing does not mean that output is *not* printed to the stream, there are other effects that might play a role (like thread synchronisation issues or a too small buffer – the latter admittedly not too likely, though). But *if* you flush, you're guaranteed to print the buffer to console. – Aconcagua Dec 03 '22 at 09:35
  • i tried in both in vs code ( powershell ) and windows terminal but the result was the same – Vedant Agrawal Dec 06 '22 at 10:33

0 Answers0