Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Remove and replace printed items

Tags:

c

I'm writing a program in C compiled in gcc. The question relates to homework, but the specific part I need help with is not part of the homework assignment. A similar question was asked Python - Remove and Replace Printed items, but I'm not using Python code. I've written most of the homework assignment, and now I'm trying to add features.

The first issue I'm trying to do is print out some text onto the screen, then remove that text, then print out new text onto the screen in the same spot where the first text used to be.

For example, I would like the program to print "Quick brown fox", then remove from the screen "brown fox", then print "green fox" where 'brown fox' used to be, so that "Quick green fox" is displayed lastly on screen in the same location

The other issue is to have the program respond to user inputs without using the enter key.

I think these features are possible, since I've run a program called Joe's Own Editor from my system. In it, I can press ctrl-C, which functions like an exit command, and a message is displayed "Lose changes to this file y,n,^C)?" If I then press "n", and only "n", the "Lose cha..." message is removed from the screen and the cursor location is adjusted.

Thanks.

like image 471
Yoshi Avatar asked Jan 21 '23 02:01

Yoshi


2 Answers

Use the \b (backspace) character.

printf("Quick brown fox");
int i;
for(i=0; i < 9; i++)
{
    printf("\b");
}
printf("green fox\n");

I noticed that putting a \n on the first printf() messed up the output.

like image 53
jonescb Avatar answered Jan 30 '23 08:01

jonescb


Doing those console manipulations is dependent on the platform that you are using. You will probably need a library to accomplish what you are trying to do. See something like this which is cross platform, or the old conio library for DOS if you're on Windows.

like image 39
jonsca Avatar answered Jan 30 '23 08:01

jonsca