Cout in While loop Strange behaviour - c++

My code look like below
int i=0;
while(i<10){
cout<<"Hello";
sleep(1);
i++
}
In Windows the code prints on each loop but in Linux it prints everything after exiting while loop . And also if I put an endl at the last of cout then it prints on each loop. Why this happening ?. Can anyone explain this behavior?.

Try to use cout.flush(); maybe the two OS has different policy in term of buffering the stdout.

For efficiency reasons, sometimes the standard streams will be implemented with a buffer. Making lots of tiny writes can be slow, so it will store up your writes until it gets a certain amount of data before writing it all out at once.
Endl forces it to write out the current buffer, so you'll see the output immediately.

#include <iostream>
using namespace std;
int main()
{
int i = 0;
while(i < 10){
cout << "Hello" << endl;
sleep(1);
++i;
}
}

Related

c++ stdout flushes stream unexpectedly

#include <iostream>
#include <thread>
using namespace std;
int main()
{
for (int i = 0; i < 10000; i++) {
cout << "Hello\n";
}
this_thread::sleep_for(chrono::milliseconds(2000));
cout << "2 seconds have passed" << endl;
return 0;
}
In my code, I didn't call any std::flush or std::endl, but the hello's are printed before the 2 seconds delay. I am expecting to print all the hello's after the 2 seconds delay, but it didn't. My code runs like this:
Hello
Hello
.
.
.
Hello
Hello
(after 2 seconds)
2 seconds have passed
[terminated]
Why is this happening?
First of all, you're writing more output than a typical file buffer will hold, so you'd almost always expect at least some of the output to show up before the sleep.
Second, you're doing a lot of separate output calls, so if cout is unit-buffered, each one is going to be flushed immediately.
Third, you're writing a new-line at the end of each item, so if cout is line-buffered, (yup) each one is going to be flushed immediately.
So, if you want a better chance of seeing at least some of the output showing up after the sleep ends, turn off unit buffering and get rid of the new-lines:
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main()
{
cout << nounitbuf;
for (int i = 0; i < 1000; i++) {
cout << "Hello";
}
// display something different to make it easier for user to see
// whether all output showed up before sleep or not.
cout << "...";
this_thread::sleep_for(chrono::milliseconds(2000));
cout << "2 seconds have passed" << endl;
return 0;
}
But even with this, there's no guarantee the behavior will change. Rather the contrary, most implementations go to some pain to assure that output written to the console shows up as promptly as possible, so even when you take steps toward delaying it, it'll still probably show up before the sleep. But this might improve your chances a little bit anyway.

Design of a simple progress bar to cout goes from 0->100% instantly at the end in C++

I would like to make a very basic progress indicator by printing an 'X' char to cout every time a loop progresses another 10%. I am trying to do this as shown in the code pasted below, but it doesn't seem to be working - when really it seems it should.
It's supposed to display steady progress throughout the loop, but instead I get all the X's coming at once after the loop has finished. This is not because the loops are completed too quickly for me to perceive. To verify this you can add an extra 'F' to "TOTAL" to increase the duration of the looping substantially, and you'll see it's not just a question of perception.
Any ideas what might be causing this?
#include <iostream>
#define TOTAL 0xFFFFFFF
using namespace std;
int main(void) {
//Make a counter for counting loops
double counter = 0;
// Set it to trigger after each 10% of progress
double counterMax = TOTAL / 10;
cout << "Starting now..." << endl;
for (double i = 0; i < TOTAL; i++) {
// Do something... anything
i++;
i--;
// Increment the counter
counter++;
// Print an X when the counter exceeds the 10%
// trigger point, and then reset the counter.
if (counter > counterMax) {
cout << 'X';
counter = 0;
}
}
cout << endl << "Done!";
return 0;
}
System input/output calls are usually slow operations. To increase the efficiency of programs, input and output streams are often buffered, to reduce the number of calls to the operating system.
When a program needs "non-buffered" output, one solution is to use the buffered output functions, and simple "flush" the output to ensure the operating system processes any output which has been queued in any buffers.
When the output buffer is filled, or when the stream is closed, it is automatically flushed. The standard output is also automatically flushed by certain sequences, like endl. But you can trigger a flush of the standard output at any point by called cout.flush() or by using the flush manipulator, like:
cout << 'X' << flush;

Simple program, cannot get for loop to execute

Brand new programmer, so green behind the ears that I could be a frog. The intent of this program is to use a for loop (not a simple formula) to add all integers up to a user designated value. It executes all code up to the for loop perfectly, however the for loop does not seem to run. Here is the code in question:
#include "stdafx.h"
#include <iostream>
int main(int num=0)
{
int sum = 0;
std::cout << "This program will sum all integers up to a given value";
std::cout << std::endl << std::endl;
std::cout << "Please enter a number "<<std::endl;
std::cin >> num;
std::cout << std::endl << "You've chosen the number " << num<<std::endl;
for (int i = 1; i <= num; ++i)
sum += i;
return (sum);
std::cout << "The sum of all numbers up to " << num << " is " << sum;
}
Any help is appreciated!
When it meets return for the first time, the program will be end.
Please put the return at the end of main function.
One more thing, shouldn't use parameter num in main function.
Write a separately function sum_all_integers and then call it in main function.
Good news: your code works! The issue is that when return (sum); is called, the function is exited, and the line that would print out your answer is not executed.
I would also recommend adding the using namespace std; line after your includes, so that you don't end up with so much std:: pollution. Also main should not take any arguments, so put that int num=0 line inside the main block.
Oh, you should also be aware of your return line indentation.
In this section
for (int i = 1; i <= num; ++i)
sum += i;
return (sum);
Your program will exit.
This boils down to what other answers have mentioned: return from main means exiting the program. Keep in mind that is is true even from within a loop like while or for - doing so is how one might design a search function which exits as soon as it has a result, for example.
To exit a for loop prematurely, use break. To continue to the next iteration and skip further code in the loop, use continue.
Also note that the indentation of return is misleading - it will be executed after the for loop, since the lack of brackets ({}) will make for only loop through the next line, which is sum += i; Keep in mind that C++ is not a whitespace sensitive language, so indentation means nothing to the logic (I like to abuse this in large blocks of similar code by tab-aligning). This is also a good example of why it is common practice to use brackets even when not strictly necessary. EDIT See also Apple's infamous "goto fail" bug.
You return the sum right after the loop:
for (int i = 1; i <= num; ++i)
sum += i;
return (sum);
This means, you sum up the numbers and then exit the program before you print the result.

delay output in c++ on linux

I want some random characters to be printed to console and then deleted by "\b". After this I want to put my own variable so it will be looking like "randomizing". The problem is that it is happening too fast. I wanted to delay the output by using usleep or sleep function but when I'm using it, nothing is printed into console.
Short example:
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
char chars[]={'a','b','c','g','h','u','p','e','y'};
for(int i=0; i<8; i++)
{
cout << chars[i];
usleep(200000);
cout << "\b";
}
}
Problem is, std::cout is line-buffered. It stores all input in a buffer until a newline is encountered (or the program terminates). Use std::flush to flush std::cout explicitly:
cout << chars[i] << flush;
Notes:
since C++11, multithreading and time are standardized. That brings the std::this_thread:sleep_for function with it, which you should use for a portable >= C++11 program:
std::this_thread::sleep_for(std::chrono::milliseconds(200));
Try my little program slowtty from github.
It allows you to simulate in a pty the behaviour of an old rs232c line, by delaying the output per character as stty(1) command allows to set the baudrate.
You call it with
$ slowtty
$ stty 1200
$
and the terminal begins to write characters at a slow pace (like a 1200baud line)
On many systems output is buffered.
To ensure that what you sent out to cout has really been flushed out of buffers you need to call
cout.flush();
before the sleep

c++, sleep, and loops

Ok, this is just out of curiousity, but why does the sleep function NOT work in a loop, or how can I Get it to work in a loop?
for(int i = 0; i < 5; i++) {
cout << i << endl;
sleep(2);
}
cout is buffered, meaning its contents aren't always written to the console right away. Try adding cout.flush() right before sleep(2);
If that isn't working for you you could try this code:
#include <iostream>
#include <windows.h>
...
for(int i = 0; i < 5; i++) {
cout << i << endl;
Sleep(2000);
}
Have you tried unrolling the loop to see if that behaves the same way?
cout << 1 << endl;
sleep(2);
cout << 2 << endl;
sleep(2);
// Etc.
Assuming that behaves the same way, even though std::endl is supposed to flush the buffer, it really does look like dave.kilian has the right idea that cout isn't getting flushed until the program (presumably) terminates.
In that case, try doing the std::flush and see if that helps - it's possible you have a bug (missed feature?) in your standard library.
Another thing to try is to redirect the output to a file while watching it with tail -f in another window. See if the same delay occurs when redirected.
Finally try playing with the compiler's optimization level and see if that changes the results.
In my humble opinion, this program should work correctly. Maybe your std::cout is redirected somewhere else? You don't call the correct sleep() function (but no header provided)? Or other problem? But it should work.
Dave has already given you the answer, so I won't touch on that. However, if its purely for debugging or prototype code, you could also pipe the output to std::cout's sibling, std::cerr, which is unbuffered to begin with. This means you do not need to call flush explicitly and you do not need to add an endl to your output.
Try Sleep() instead of sleep()