Reputation:
I'm a beginner at coding and I was instructed to code a text-based game so I am trying to figure out whether it's possible to print out a statement for a limited time only in C and is it also possible to let them input an answer for a limited time as well? The problem is if I print out something, they could scroll up and that's what I'm trying to avoid. If it is possible, please do enter the code or resources that I may use for reference below. Thank you.
Upvotes: 1
Views: 202
Reputation: 16540
use the ANSI escape commands to 1) remember where the cursor currently is located 2) printf the line (and remember the returned value from printf()
3) start a timer (for instance using alarm()
) when the timer/alarm expires a signal will be raised. Use the signal to flag the event, then in the main code: if signalflag asserted, use ANSI escape sequence to move the cursor to the saved/remembered position, then write space data for the length returned from the original printf()
. Then restore the cursor
Upvotes: 0
Reputation: 1917
You could print backspaces to delete the text you just displayed. Like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main() {
char * string = "Hello";
printf("%s", string);
fflush(stdout);
sleep(1);
char * backspaces = malloc(strlen(string) * sizeof(char));
for (int i = 0 ; i < strlen(string) ; i++) backspaces[i] = '\b';
printf("%s", backspaces);
}
And for the limited time valid input you could use gettimeofday to check if input is within time or not.
Upvotes: 0
Reputation: 3162
you can use \r
to take the print cursor to begining of line. so you can replace that content to achieve the effect of deleting the content after sometime
Upvotes: -1
Reputation: 385274
Terminals are, by default, designed to emit progressively more and more lines of text in a buffer. Text gets added to the end, and previous lines remain visible (up to the limit of the terminal's configured buffer size).
It is possible to get more of a "GUI" feel by changing terminal modes, and this is usually done using a library like curses or ncurses. This will permit you to show text at specific parts of the window, and remove said text. Upon ending the program, curses "resets" the terminal such that the whole "GUI" disappears (although some terminals will still show the user the "final state" of the GUI if they scroll up a page).
A code example would be a tutorial on how to use ncurses, which is a bit too broad for this medium, but not difficult to find.
Since you're on a beginner course, it's likely that you are being encouraged to do the next best thing, which is either:
In all cases described above except for #3, the responsibility of implementing a "timer" shall be yours.
Upvotes: 4