Can sleep() in c++ in unix environment be used as the same as delay() in Turbo C++ for windows? - delayed-execution

In Turbo C++:
while(i<10)
{delay(100);
cout<<"*";
i++;}
will print "*" after a regular intervals of 100 milliseconds. If I try to do the same in C++ in UNIX like:
while(i<10)
{
sleep(1);
cout<<"*";
i++;}
it prints "*" 10 times after a single interval of 10 seconds at once.
Please, can someone explain why is it not working.

Because cout is often buffered by default. If you want it printed immediately, flush it:
std::cout << "*" << std::flush;

Related

Printing in c program with delay?

I'm trying to print something like:
Exiting...
into a terminal when the program ends, but the way I want it to be outputted to the terminal is each dot after "Exiting" needs to be printed with a slight delay after each other in the same line. Like it is loading to put it that way. But I have no idea how to make it print each of them separately without the whole line to be printed all at the same time. I'm mot sure if that is possible in c in the first place.
I've tried adding delay between each printf using time but that did not work.
You can use it like this -
cout<<"Exiting";
cout.flush();
for (int j=0;j<1;j++) {
for (int i = 0; i < 3; i++) {
cout << ".";
cout.flush();
sleep(1);
}
cout << "\b\b\b \b\b\b";
}
cout<<"\n\n";
sleep(1);
I was stuck with the same problem where I had to print something with delay.
This thing works flawlessly.
P.S - Use the required Header Files.

Print, delay and erase current line in C

I want to print the seconds elapsed in real time since the program began. First the output is "0". After one second, the "0" is replaced by "1", and so on. Here is the code I wrote initially.
#include<stdio.h>
#include<time.h>
void main ()
{
long int time;
printf("Hello, let us measure the time!\n");
time=clock();
printf("%ld", 0);
while(time/CLOCKS_PER_SEC<7)
{
time=clock();
if(time%CLOCKS_PER_SEC==0)
{
printf("\r");
printf("%ld", time/CLOCKS_PER_SEC);
}
}
}
This gave an output "7" at the end of 7 seconds only.
If I make the following replacements, the code works fine.
printf("%ld", 0);
by
printf("%ld\n", 0);
and
printf("\r");
printf("%ld", time/CLOCKS_PER_SEC);
by
printf("\33[A"); //vt100 char, moves cursor up
printf("\33[2K"); //vt100 char, erases current line
printf("%ld\n", time/CLOCKS_PER_SEC);
The problem seems that the output wont be sent until the current line is completely determined. What is happening here?
I am using gcc compiler on Ubuntu.
The output stream that you are writing to with printf() will buffer until the newline is received. Since you aren't sending a newline then you get no flush until your application exits or the buffer fills up.
You can flush the output buffer yourself after each printf(), as hyde said in the comment above using fflush(stdout).
Or you can disable buffering by using setbuf( stdout, NULL );

Raspberry Pi: printf() doesn't work with wiringPi

I'm trying a simple code that using wiringPi as here:
#include<wiringPi.h>
#include<stdio.h>
int main(void){
int i;
wirintPiSetup();
pinMode(0,OUTPUT); //a single LED
pinMode(8,INPUT); //tactile switch
for(;;){
delay(500);
//push tactile switch and LED is turning on
if(digitalRead(8)) digitalWrite(0,0);
else digitalWrite(0,1);
printf("%d",digitalRead(8));
}
}
I expected a result of printf() is output to console,
but it doesn't work.
printf() couldn't run in same time with wiringPi APIs?
no warnings at compile. and CPU consumption is always under 4%.
running on Raspbian.
Thanks for your time!
stdout by default is typically line-buffered, meaning it tries to put off writing data to the underlying file until a newline. But since you never print a newline, stdout will just buffer your text until it runs out of space.
You can fix this by either adding a newline in the format string (i.e. "%d\n"), or calling fflush on stdout after printing.

delay function using clock()

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void delay(double sec)
{
clock_t start = clock();
while ((clock() - start) / CLOCKS_PER_SEC < sec)
;
}
int main()
{
for (int i = 0; i < 100000; i++) {
printf("%d ", i);
delay(1);
}
return 0;
}
I wrote a delay function and tested it with this code, but I didn't see any number in standard output.
Then I changed the printf() call like this :
printf("%d \n", i);
Interestingly, it worked. I also tried without delay function like this:
for (int i = 0; i < 100000; i++)
printf("%d ", i);
It also worked. What am I missing here? Why can't I see any number when I run the first code? Thanks for helps :)
Because the output is buffered. Most terminals will buffer the standard-output until either a newline (\n) is encountered, or fflush(stdout) is called.
Your loop that includes the call to delay should eventually print the numbers, but when the program is finished.
Add fflush(stdout); after the printf-call to make the numbers appear immediately without newlines in between.
Well, there are two reasons. First, printf() doesn't always flush its output, so you may actually get past the printf statement and still not see anything on your terminal. The text is buffered. Putting in a \n may have caused it to flush its output, so that's why that worked.
The second problem is that you are not passing any value to your delay() function. So it's probably using some random value, and hanging.
I'd also like to point out that clock() returns CPU time, not "wall clock" time, so it may actually take longer than you think.
Delay functions are tricky, that's why there are lots of system calls to do them. See sleep().

How to pause between functions in a program in C with GCC?

So my problem is my program runs too fast that I can't see how it behaves. It's supposed to make the text crawl along the edges of the terminal. I tried to use sleep() to make a short pause betweenprintf(...)s so that it I can see where the text us going while it prints.
This is what it looks like:
http://i.imgur.com/B6FFbNp.gif
So I put sleep() function after the printfs so that it will pause before starting the loop again and make the text move slowly. But what happens is it pauses the programs indefinitely before it even starts. This also happens with usleep and system("pause 1"). This is what it looks like:
http://i.imgur.com/krGW3lB.gif
==================================================================================
EDIT:
Okay, I figured it out on my own. It seems that sleep() only works if I put \n in my strings. I don't know why. I didn't even read this in the damn manuals.
So if you have
printf("HELLO\n");
sleep(3);
printf("HELLO\n");
sleep(3);
printf("HELLO\n");
It will result in:
HELLO
[pause for 3 seconds]
HELLO
[pause for 3 seconds]
HELLO
but if you remove the newline characters it will:
[pause for 9 seconds]
HELLO HELLO HELLO
I don't know why this happens but it just does
==================================================================================
EDIT:
This is how I wanted my program to work:
http://i.imgur.com/DXv7E60.gif
Thank you for your answers
Your observations do not due to sleep() not working, but to the fact that printf() uses stdout, which is line buffered. "line buffered" means, that what has been written to stdoutis buffered until the end of the line is reached before the buffer's content it is flushed out.
So after the first printf("HELLO"); the output does not go to the screen but stays in the buffer, then sleep(1); is executed and makes you wait. Then for the next printf("HELLO"); the output still does not go to the screen, but the following sleep(1); again makes you wait for 1 second ... and so on until a line end if reached by your program printing a '\n' or by the program's end, which implicitly flushes the output buffer to the console.
You can avoid the behaviour by flushing stdout's output buffer explicitly after every printf():
#include <stdio.h>
#include <unistd.h>
int main(void)
{
printf("HELLO");
fflush(stdout);
sleep(3);
printf("HELLO");
fflush(stdout);
sleep(3);
printf("HELLO");
/* fflush(stdout); */ /* not needed as buffers are implicitly flushed on the program's end */
return 0;
}
A quick hack I usually do is make some buffer array (eg. char buf[10]) and place an fgets() in between iterations, which forces the program to wait for a newline from the user. So, for example, if we had:
.
.
.
for(i = 0; i < 1000000; ++i)
printf("%d\n", i);
we could then do
.
.
.
char buf[10];
for(i = 0; i < 1000000; ++i){
printf("%d\n", i);
fgets(buf, 10, stdin);
}
and control the iterations with the enter key.
We could also stop every nth iteration by using a modulus. Using the above example, we will now stop every 100 iterations:
.
.
.
char buf[10];
for(i = 0; i < 1000000; ++i){
printf("%d\n", i);
if(i % 100 == 0)
fgets(buf, 10, stdin);
}
A more time consuming but effecient way is to use a dedicated debugger like GDB.

Resources