Print out seconds on screen by replacing them without clear screen - c

I've tried but still dont know yet. I want to print out the result like this: seconds(10) -> seconds(9) -> ... -> seconds(1) by replacing each integer in every second without system("cls").
sample program

You could print \r to return the cursor to the beginning of the line.
Example:
#include <stdio.h>
#include <threads.h>
int main() {
struct timespec st = {.tv_sec = 1, .tv_nsec = 0};
for(int i = 10; i>=0; --i) {
printf("%2d\r", i); // \r to return to the beginning of the line
fflush(stdout); // flush to ensure it's actually printed
thrd_sleep(&st, NULL); // sleep a second
}
}

Related

How to print to terminal one char and then pause and print another?

I've been trying to print to the terminal with a pause, it's better explained with the following code:
I'm trying to have X print to the terminal and then wait 5s and have X print again but when I run the code, it waits 5s and prints XX can anyone help me get the proper functionality?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static void sleepMs(long long delayMs){
const long long NS_PER_MS = 1000 * 1000;
const long long NS_PER_SECOND = 1000000000;
long long delayNs = delayMs * NS_PER_MS;
int seconds = delayNs / NS_PER_SECOND;
int nanoSeconds = delayNs % NS_PER_SECOND;
struct timespec reqDelay = {seconds, nanoSeconds};
nanosleep(&reqDelay, (struct timespec *) NULL);
}
int main()
{
printf("X");
sleepMs(5000);
printf("X");
return 0;
}
Thank you in advance, sorry for any missing tags.
EDIT: I want them to print on the same line
You need to flush the output stream if you want to see the result before printing a \n:
putchar('X');
fflush(stdout);

C: variables retain the value from previous operation instead of resetting

I am fairly new to C and have been trying my hand with some arduino projects on Proteus. I recently tried implementing a keypad and LCD interface with Peter Fleury's libraries, so far the characters I input are displayed fine, but I run into a problem when trying to print to the serial port. It's like the value of the keys keeps on being concatenated with every iteration so the ouput has extra characters like this:
The value before the comma is from the 'key' variable, the value after it the 'buf' variable:
151
(The 5 I input in the second iteration was added to the 1 from the first iteration and then put into the variable I print)
I figure it may be due to my lack/incorrect use of pointers, heres is my code:
#include <avr/io.h>
#include <util/delay.h>
#include <stdlib.h>
#include <stdio.h>
#include "lcd.h"
#include "mat_kbrd.h"
#include "funciones.h"
#include "menu.h"
char buf[256];
char* coma = ",";
int main(void)
{
pin_init();
serial_begin();
lcd_init(LCD_DISP_ON);
kbrd_init();
bienvenida();
while (1) {
int i = 0;
char key = 0;
//char *peso;
//int pesoSize = 1;
char peso[100];
//peso = calloc(pesoSize,sizeof(char));
int salida = 0;
lcd_clrscr();
desechos();
key = kbrd_read();
if (key != 0) {
lcd_gotoxy(0,3);
lcd_putc(key);
_delay_ms(2000);
lcd_clrscr();
cantidad();
while (salida != 1) {
char keypeso = 0;
keypeso = kbrd_read();
//pesoSize = i;
//peso = realloc(peso,pesoSize*sizeof(char));
if (keypeso != 0) {
if (keypeso == '+') {
salida = 1;
keypeso = *("");
lcd_clrscr();
calcularTotal(key,peso);
_delay_ms(2000);
} else {
lcd_gotoxy(i,1);
lcd_putc(keypeso);
snprintf(peso, sizeof peso, "%s%s",peso, &keypeso);
//strcat(peso,&keypeso);
i++;
_delay_ms(2000);
}
}
}
snprintf(buf, sizeof buf, "%s%s%s", &key,coma,peso);
serial_println_str(buf);
}
}
}
&key and &keypeso point to a single char, but you are using the %s format specifier, so trying to read a string into a single char. Use %c rather then %s for single characters, and pass the char not the address-of-char..

problems utilitizing small pauses in c code using nanosleep

I am a C beginner and trying this and that.
I want to display a string letter by letter with tiny pauses in between. So my idea was a small pause using sleep or usleep after displaying each char but I read that using nanosleep in your own function makes more sense. So I put my little pauses in a function "msleep" to get microseconds pauses.
I output my string 3 times.
Once in the main(), then in a do-while-loop in a function (fancyOutput) char by char, and eventually in the same function with printf again to check, if it was handled over correctly.
My problem: I expected, that the middle output would work char by char and separated by 100/1000 seconds breaks, but what I experience is a long break before chowing any char and then a fast output if line two and three. It looks like the compiler "realized what I am planning to do and wants to modify the code to be more efficient." So all my pauses seemed to be combined in one long break.
Maybe you remeber the captions in the tv series "x files" - something like that I want to produce.
For sure there are better and more sophisticated ways to archieve what I am going to try but I want to learn and understand what is going on. Can someone help me with that?
I am using codeclocks on a debian-based distro with gcc.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int msleep(long tms);
void fancyOutput(char inputToOutput[]);
int msleep(long tms)
{
struct timespec ts;
int ret;
if (tms < 0)
{
return -1;
}
ts.tv_sec = tms / 1000;
ts.tv_nsec = (tms % 1000) * 1000000;
do
{
// printf("sleeping for %d", ret);
ret = nanosleep(&ts, &ts);
}
while (ret);
return ret;
}
void fancyOutput(char inputToOutput[])
{
int counter = 0;
do
{
printf("%c", inputToOutput[counter]);
msleep(100);
++counter;
}
while (!(inputToOutput[counter]=='\0'));
printf("\n");
printf("%s\n", inputToOutput); // only check, if string was properly handled over to function
}
char output[] = "This string shall appear char by char in the console.";
void main(void)
{
printf("%s\n", output); // only check, if string was properly set and initialized
fancyOutput(output); // here the function above is called to output the string char by cchar with tiny pauses between
}
You are getting problem with buffer.
When you use printf with no \n (new line) C is buffering the display in order to display information block by block (to optimize displaying speed).
Then you need to either add a \n to your printf or add a flush of the stdout.
An other solution will be to use stderr, which got no buffer, but stderr is meant for error not output :)
You can also check setvbuf in order to change the buffering.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int msleep(long tms);
void fancyOutput(char inputToOutput[]);
int msleep(long tms)
{
struct timespec ts;
int ret;
if (tms < 0)
{
return -1;
}
ts.tv_sec = tms / 1000;
ts.tv_nsec = (tms % 1000) * 1000000;
do
{
// printf("sleeping for %d", ret);
ret = nanosleep(&ts, &ts);
}
while (ret);
return ret;
}
void fancyOutput(char inputToOutput[])
{
int counter = 0;
do
{
printf("%c", inputToOutput[counter]);
flush(stdout);
msleep(100);
++counter;
}
while (!(inputToOutput[counter]=='\0'));
printf("\n");
printf("%s\n", inputToOutput); // only check, if string was properly handled over to function
}
char output[] = "This string shall appear char by char in the console.";
void main(void)
{
printf("%s\n", output); // only check, if string was properly set and initialized
fancyOutput(output); // here the function above is called to output the string char by cchar with tiny pauses between
}
So, I tried the solution to place fflush(stdout); directly after the char-output in the loop. It worked as intended.
Summarizing for those with similar problems (guess this also happens with usleep and similar self-made functions):
As I understaood, printf "collects" data in stdout until it "sees" \n, which indicates the end of a line. Then printf "releases" stdout. So in my initial post it "kept" each single char in stdout, made a pause after each char and finally released stdout in one fast output.
So fflush(stdout); after each char output via empties stdout char by char.
Hope it can help others.

C sleep method obstructs output to console

I have a C program, where I just wanted to test if I could reproduce a console spinner used in npm install while it installs a module. This particular spinner simply spins in this order:
|
/
-
\
on the same space, so I use the following program:
#include <stdio.h>
int main() {
char sequence[4] = "|/-\\";
while(1) {
for(int i = 0; i < 4; i++) {
// \b is to make the character print to the same space
printf("\b%c", sequence[i]);
// now I want to delay here ~0.25s
}
}
}
So I found a way to make it rest for that long from <time.h> documentation and made this program:
#include <stdio.h>
#include <time.h>
void sleep(double seconds) {
clock_t then;
then = clock();
while(((double)(clock() - then) / CLOCKS_PER_SEC) < seconds); //do nothing
}
int main() {
char sequence[4] = "|/-\\";
while(1) {
for(int i = 0; i < 4; i++) {
printf("\b%c", sequence[i]);
sleep(0.25);
}
}
}
But now nothing prints to the console. Does anyone know how I can go about producing the behavior I want?
EDIT According to what appears to be popular opinion, I've updated my code above to be the following:
#include <stdio.h>
#include <unistd.h>
int main() {
char sequence[4] = "|/-\\";
while(1) {
for(int i = 0; i < 4; i++) {
printf("\b%c", sequence[i]);
/* fflush(stdout); */
// commented out to show same behavior as program above
usleep(250000); // 250000 microseconds = 0.25 seconds
}
}
}
You will need to flush after you wrote to the console. Otherwise, the program will buffer your output:
fflush(stdout);
Things do get printed to console, it's just does not get flushed. Add fflush(stdout) to see the results, or set the console in an unbuffered mode by calling setbuf:
setbuf(stdout, NULL);
A bigger problem with your code is that your sleep method runs a busy loop, which burns CPU cycles for no good reason. A better alternative would be to call usleep, which takes the number of microseconds:
usleep(25000);
The sleep function isn't really your problem. The issue is that the output is buffered. The simplest thing to do will be to research ncurses.
For now:
fflush(stdout);

Ncurses - multiple windows and refreshing

I'm writing a small school project. It's a game of falling words - the word is moving from the top to the bottom. I had an idea to make two windows (one with interface and second with moving object). Words are randomized as you can see in the code. The problem is the input. I'm using mvwsacanw to write the word. Is there any way to write anything in second window while the word is moving in different window? For now the word is falling and when it reaches the bottom, the second window opens and I can type the word.
Hope somebody will help me.
#include <stdio.h>
#include <ncurses.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
void moving(WINDOW *move)
{
int j,random;
char *cmp=(char*)malloc(10*sizeof(char));
char word[6];
wclear(move);
box(move, 0, 0);
mvwprintw(move, 1, 1, "PIS");
wrefresh(move);
srand (time (NULL));
random=2+rand()%7;
for(j=0; j< random ; j++) //random word
{
word[j]= rand()%26+'a';
}
int poz = 2+rand()%24; //random position of moving word
for(int i=1; i<18; i++)
{
wclear(move);
box(move,0,0);
mvwprintw(move,i, poz, word);
wrefresh(move);
usleep(300000);
}
}
void interface(WINDOW *ui)
{
wclear(ui);
char *cmp=(char*)malloc(10*sizeof(char));
box(ui, 0, 0);
mvwprintw(ui,1,1,"wpisz wyraz: ");
mvwscanw(ui,2,1, "%s",cmp);
mvwprintw(ui, 3, 1, "->%s",cmp);
wrefresh(ui);
}
int main(int argc, char *argv[])//int argc, const char * argv[])
{
int x,y;
int sc = 3;
initscr();
noecho();
curs_set(FALSE);
getmaxyx(stdscr, y,x);
WINDOW *move = newwin(y-5, x-1, 0, 0);
WINDOW *ui = newwin(sc+2, x, y-5, 0);
while(1)
{
moving(move);
interface(ui);
wclear(move);
wclear(ui);
}
delwin(move);
delwin(ui);
endwin();
return 0;
}
You can't do that with your current code structure. You are keeping the word fall phase and the input phase in separate functions, so the only way to make them work at the same time is some kind of multithreading.
Assuming this is not what you want to do, you could try to merge the two features in a single function. In pseudocode:
pick random word
pick random position
set i = 0
set input = {} //empty array
do
> print word at (i, pos)
> set stoptime = time() + DELAY
> do
>> set c = getch()
>> append c to input
>> print interface
> while (time() < stoptime)
> i++
while (i < 18)
This, with timeout() set to an opportune delay, will give the impression that everything is happening simultaneously.
This is absolutely not the most efficient solution, but is simple and straightforward, and considering you are working on a school project, it should be just fine
Try to use the following code :
nodelay(your_window, TRUE);
which will make your input nonblocking for the given window !

Resources