Following program prints 1 2 3 4 5 at once. That means there is no time delay in printing the output.
#include<iostream>
#include<stdio.h>
#include <thread>
using namespace std;
int main()
{
for(int i = 1; i <= 5; ++i)
{
cout << i << " ";
// Function to sleep the thread
this_thread::sleep_for(500ms);
}
return 0;
}
But this program prints
1
2
3
4
5
one by one that means I’m getting the output with 0.5 sec time delay.
#include<iostream>
#include<stdio.h>
#include <thread>
using namespace std;
int main()
{
for(int i = 1; i <= 5; ++i)
{
cout << i << "\n";
// Function to sleep thread
// for 0.5 sec
this_thread::sleep_for(500ms);
}
return 0;
}
What is literally happening in both of above programs?
Note:You can't see the difference of both the outputs in online compiler because they show the result after termination of program.
The output may be line buffered, in which case only complete lines are sent to the underlying output device.
I'm able to get the desired output, one element at a time appears with 0.5 sec of delay. Used visual studio 2015.
I suggest you to avoid online compilers.
They generally give the complete output once in a text box.
"\n" makes the output go to next line. It is newline character
Related
#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.
I am making a loading type function so what I wanted to do was to halt my program for a few seconds and then resume the execution inside a loop to make it look like a loading process. Looking up on web I found that I can use std::this_thread::sleep_for() to achieve this (I am doing this on linux). The problem I am facing is that I am unable to make it work with \r or any other way to overwrite the last outputted percentage as the program freezes as soon as I do it, however it works perfectly with \n and it's all confusing to understand why it'd work with a newline sequence but not with \r.
I am posting the sample code below, can someone tell me what am I doing wrong?
#include<iostream>
#include<chrono>
#include<thread>
int main()
{
for (int i = 0; i<= 100; i++)
{
std::cout << "\r" << i;
std::this_thread::sleep_for(std::chrono::seconds(rand()%3));
}
return 0;
}
I am kinda new to this topic and after some digging I found out that I am messing with the threads. But still not sure why this behavior is happening.
This works fine on my machine (Windows 10):
#include <iostream>
#include <chrono>
#include <thread>
#include <cstdlib>
#include <ctime>
int main( )
{
std::srand( std::time( 0 ) );
for ( std::size_t i { }; i < 100; ++i )
{
std::cout << '\r' << i;
std::this_thread::sleep_for( std::chrono::seconds( std::rand( ) % 3 ) );
}
}
I suggest that you write '\r' instead of "\r" cause here you only want to print \r character and "\r" actually prints two characters (\r and \0).
Also, it's better to seed rand using srand before calling it.
However, it may not work as expected in some environments so you may need to flush the output sequence like below:
std::cout << '\r' << i << std::flush;
or like this:
std::cout << '\r' << i;
std::cout.flush( );
These are equivalent.
For more info about flush see here.
#include "stdafx.h"
#include "iostream"
#include "thread"
#include "conio.h"
#include "windows.h"
using namespace std;
void incrm();
void charget();
void main() {
thread count(incrm);
thread getcin(charget);
count.join();
getcin.join();
cin.get();
}
void incrm() {
int j = 0; // used to increment and output
while (true) {
cout << "\r" << j; // outputs 1,2,3,4... and so on
j++;
Sleep(150);
}
cout << endl;
}
void charget() {
while (true) {
int i = getch(); // gets value of char
cout << "\r\nCHAR: " << i; // and here is the problem...!
}
}
So I wanted this program to output a number in the first line, which increments without stopping and if you hit any key it should cout the value of that key in a secound line, so i wanted it to output something like this->
45
CHAR: 97
and after you have hit a key the incrementing number should stay in the first line. If you hit several keys the second cout should be overwritten, but this doesnt seem to work for me, my output looks like this if i hit several keys->
10
12AR: 97
20AR: 96
My problem is that my first cout (the incrementing number) overwrites my second (or my second my first I don't really know) and then this countinues for every line! :(
I suggest you to use windows function called gotoxy(). You can apply this using
SetConsoleCursorPosition();
this function is availible in windows.h library.
It is possible to read more about it here:
Link
This question already has answers here:
std::cout won't print
(4 answers)
Closed 9 years ago.
So, I have the program below. What it does is, it prints random numbers while formating them with a width of 10 on the console.
Now, when I added the sleep function, I expected it to print one number every 10 milliseconds (or more), but what it does is, it prints 100 outputs every 100*10 milliseconds. I was wondering, why does this happen? Does the output get buffered or what?
#include <unistd.h>
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <iomanip>
int main()
{
srand(time(0));
for (int i = 1; i < 1000000; i++)
{
usleep(10*1000); // No matter the input, the same thing happens
cout << setw(10) << rand()%(90*i) + 10*i;
}
}
I tried this both on windows and unix and it's the exact same thing.
Yes, the output does get buffered.
Use std::cout.flush(); to flush manually.
As a note, std::endl (appends a new line and) does the flush.
When I write every C++ program, such as that one:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
cout << "Tell me where to start: ";
cin >> n;
while (n>0) {
cout << n << "\n";
n = n-1;
}
cout << "FIRE!";
return 0;
}
I compile it with G++ and, when I run it, it works well, but when it finishes it displays the "logout" word after the program's last word, like this:
Tell me where to start: 10
10
9
8
7
6
5
4
3
2
1
FIRE!logout
[Process completed]
Why? And how can I remove it?
It's not from your program. It's because the terminal is opened with the sole purpose of running your program, and as such when it exits, the terminal shuts down.
If you open a shell and manually run your executable, instead of this message, you'll simply get another command prompt.