How to delete random number sequence - c

I am new to C programming.
I am trying to work through an example in my textbook.
Problem:
1 : Can't make random number generator pause for one second, without having to
insert printf(); in a place where I shouldn't.
2: Can't make the program pause for 1 second, and then delete random sequence. I have tried using printf(\r), but it just deletes the entire sequence without pausing for 1 second.
Help appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
time_t Start_Of_Seq = (time(NULL));
time_t Now = 0;
Now = clock();
srand((unsigned int)Start_Of_Seq);
for(int i = 1; i <= 5; i++)
{
printf("%d",rand()% 10);
}
printf("\n"); //This shouldn't be here.
for(; clock() - Now < CLOCKS_PER_SEC;);
printf("Testing the to see if there is a pause\n");
}

The printf function outputs everything to a buffer. The buffer is actually printed only after a newline. Try fflush(stdout); to print the buffer contents immediately.
Besides, if you use Linux or another Unix-like system, for pauses there is a system call sleep. Try the man 3 sleep command to see more info.

Related

Not seeing initial output of printf when I try to rewrite over the same line 5 seconds later

I'm trying to reproduce from code from Ivor Horton's Beginning C. I couldn't get the results that the code is expecting so I wrote a smaller program with the specific code that I'm having a problem with.
Please see the first for loop. It should print out two random numbers. If I comment out the second for loop which creates an approximate 5 second delay and the subsequent printf("\rHello) I will see the two random numbers. However if I uncomment the second for loop and the subsequent printf, I will never see the two random numbers, only the output Hello, even though the for loop delays the printf("\rHello") for 5 seconds. I thought I would be able to see the two random numbers for at least 4 seconds or so before they are overwritten by the printf("\rHello"). Can anybody tell me what is going on here?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <stdlib.h>
int main(void) {
clock_t wait_start = 0;
time_t seed = 0;
unsigned int digits = 2;
unsigned int seconds = 5;
wait_start = clock();
srand((unsigned int) time(&seed));
for (unsigned int i = 1; i <= digits; ++i)
printf("%u ", rand() % 10);
// printf("%Lf\n", ((long double)clock()) / CLOCKS_PER_SEC);
for (; clock() - wait_start < seconds * CLOCKS_PER_SEC; )
;
// printf("%Lf\n", ((long double)clock()) / CLOCKS_PER_SEC);
printf("\rHello");
return 0;
}
The suggested answer is good, if you know what you're looking for. The title of my question is very straight forward literal explanation of what is happening in my code. A beginner may not search for "flush" and "stdout buffer". I didn't search for that and didn't find this solution to my question. It is complementary to the solution to this question to give more understanding to the beginner. The solution to my question gave a straight-forward solution to my question, and then it was followed with more information giving insight as to why I need to use fflush.
The reason the random digits do not appear is you do not flush the stdout stream to the terminal and since you did not output a trailing newline, it is pending in the stream buffer because stdout is usually line buffered by default when attached to a terminal.
Note also that waiting for 5 seconds with a busy loop asking for elapsed CPU time is wasteful. You should instead use a sleep() system call or the equivalent call on the target system (probably _sleep() on Microsoft legacy systems).
Here is a modified version:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#if defined _WIN32 || defined _WIN64
#include <windows.h>
#else
#include <unistd.h>
#endif
int main(void) {
int digits = 2;
int seconds = 5;
srand((unsigned int)time(NULL));
for (int i = 0; i < digits; i++) {
printf("%d ", rand() % 10);
}
fflush(stdout);
#if defined _WIN32 || defined _WIN64
Sleep(seconds * 1000UL);
#else
sleep(seconds);
#endif
printf("\rHello\n");
return 0;
}

Timer using a time function in C [duplicate]

This question already has answers here:
Why does printf not flush after the call unless a newline is in the format string?
(10 answers)
Closed 1 year ago.
I want to print a line and then get it erased after ten seconds.
So I thought that I should write a timer as a preliminary programme and with erasure I could deal later using whatever I find on the internet (using \r for example).
And so I want to print "I love nachos" and ten seconds later "I hate nachos".
However, even though printf("I love nachos") is written before any conditions, the programme prints both strings after ten seconds.
#include <stdio.h>
#include <time.h>
int main(void) {
printf("I love nachos");
time_t now = time(NULL);
while (1)
{
time_t future = time(NULL);
if ((future-now)==10)
{
break;
}
}
printf("I hate nachos");
return 0;
}
I asked my friend to tackle the problem and he wrote:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
printf("Start\n");
time_t t0 = time(NULL);
while ( (difftime(time(NULL), t0)) <= 10.0 )
{}
printf("End");
return 0;
}
However, in that case the programme only works with \n in printf("Start\n").
If I remove \n I get the same result as per my initial code and I obviously don't want \n there, because I wouldn't be able to erase the line with \r
The printf output to stdout is by default line buffered. That means nothing is actually sent out until either the internal buffer is full or a newline is added or the FILE is closed (as happens implicitly when the program exits)
So either add a newline or use fflush to force the buffer to be transmitted immediately to the output.

How do I implement the sleep function in my for loop correctly? (Ubuntu)

I'm trying to make my code print something to the screen, then wait 1 second, then go around the for loop and print it again 21 times. It works when I do this in Windows in CodeBlocks by using #include and then Sleep(1000). But when I'm doing it on my Ubuntu VM by using #include and sleep(1), everything disappears from my terminal for 21 seconds then all appears at once. I think I'm using the wrong function or something.
Any ideas?
This is the code in Ubuntu terminal which ends up removing everything already on my terminal, waits 21 seconds then just prints "Hello" 21 times.
#include <stdio.h>
#include <unistd.h>
int main()
{
for (int i = 0; i < 21; i++)
{
printf("Hello");
sleep(1);
}
}
This is the code in Windows which prints "Hello" every second for 21 seconds therefore printing 21 Hello's on my screen over 21 seconds. Which is what I'm trying to achieve in my Ubuntu VM.
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main() {
for (int i = 0; i < 21; i++)
{
printf("Hello");
Sleep(1000);
}
return 0;
}
In UNIX, process streams buffer - they accumulate I/O and do not "flush" to the underlying device immediately on write, per default. So - you need to flush the stream:
#include <stdio.h>
#include <unistd.h>
int main()
{
for (int i = 0; i < 21; i++)
{
printf("Hello");
fflush(stdout);
sleep(1);
}
}
It would also work if you output a newline '\n' after "Hello", I believe.
printf output is buffered - which means, it is not guaranteed to appear on the screen immediately. Rather, it appears when one of the following happens:
when the buffer becomes full, - at which time the old contents of buffer is displayed to the screen and the buffer is cleared fresh for the new output - this is called buffer flushing
when the application terminates - which forces flushing of all the printf buffers, and this is what you see on the screen
When buffer is flushed by the programmer.
The last case is most interesting for you, and there are two ways you can do this - either include \n (new line) control character in your string, like
printf("Hello\n");
or call fflush for stdout stream, like
printf("Hello");
fflush(stdout);

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().

Is it possible to wait a few seconds before printing a new line in C?

For example could I make it type something like
"Hello"
"This"
"Is"
"A"
"Test"
With 1 second intervals in-between each new line?
Thanks,
Well the sleep() function does it, there are several ways to use it;
On linux:
#include <stdio.h>
#include <unistd.h> // notice this! you need it!
int main(){
printf("Hello,");
sleep(5); // format is sleep(x); where x is # of seconds.
printf("World");
return 0;
}
And on windows you can use either dos.h or windows.h like this:
#include <stdio.h>
#include <windows.h> // notice this! you need it! (windows)
int main(){
printf("Hello,");
Sleep(5); // format is Sleep(x); where x is # of milliseconds.
printf("World");
return 0;
}
or you can use dos.h for linux style sleep like so:
#include <stdio.h>
#include <dos.h> // notice this! you need it! (windows)
int main(){
printf("Hello,");
sleep(5); // format is sleep(x); where x is # of seconds.
printf("World");
return 0;
}
And that is how you sleep in C on both windows and linux! For windows both methods should work. Just change the argument for # of seconds to what you need, and insert wherever you need a pause, like after the printf as I did. Also, Note: when using windows.h, please remember the capital S in sleep, and also thats its milliseconds! (Thanks to Chris for pointing that out)
something not as elegant as sleep(), but uses the standard library:
/* data declaration */
time_t start, end;
/* ... */
/* wait 2.5 seconds */
time(&start);
do time(&end); while(difftime(end, start) <= 2.5);
I'll leave for you the finding out the right header (#include) for time_t, time() and difftime(), and what they mean. It's part of the fun. :-)
You can look at sleep() which suspends the thread for the specified seconds.
The most easiest way is to give a loop. Be it while or for loop
int main()
{
while(i<100000) //delay
{
i++;
}
}
Works on all OS
int main()
{
char* sent[5] ={"Hello ", "this ", "is ", "a ", "test."};
int i =0;
while( i < 5 )
{
printf("%s", sent[i] );
int c =0, i++;
while( c++ < 1000000 ); // you can use sleep but for this you dont need #import
}
return 0;
}

Resources