Erase the displayed characters - c

I'm doing the exercises in the "C Programming Language" 2nd Edition by Brian W. Kernighan & Dennis M. Ritchie.
Exercise 1.9 confused me. So here it is:
"Write a program to copy its input to output, replacing each string of one more blanks by a single blank".
I puzzled over this. I post my question here because other learners didn't do this exercise the same as I want to do it. Here it is, using - to represent a blank:
Input: ----hello
Output: -hello
But I want this:
Input: ----hello
Output: ----hello
Input: ----
Output: -
So here is my program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int character; /* input character */
int non_blank = 0; /* is any non blank character */
while ((character = getchar()) != EOF) {
if (character != '\n') {
putchar(character);
if (character != ' ') {
non_blank = 1;
}
}
else {
if (non_blank == 0 ) {
putchar('\b'); /* go to previous line (blabla\n|cursor|) (blabla|cursor|\n) */
putchar('\r'); /* carriage return */
putchar(' '); /* put one space */
putchar('\0'); /* and put the end of line */
}
non_blank = 0;
}
}
return EXIT_SUCCESS;
}
But spaces aren't erased.
Input: ------|\n
Output: -|-----
Here is my experiment with escape sequences:
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("bbbbbbbbbbbbbbb");
putchar('\b'); /* jump to previous line */
putchar('\r');
putchar('b');
putchar('\0');
return EXIT_SUCCESS;
}
| is a cursor.
Output: b|
But when I'll add the newline character, it doesn't work. How to make it work with newline characters?

The problem with your code is that you are printing the characters as soon as you process them, and you try to erase them once you detect they have to be compressed to one space.
Your approach is valid, but you must know first that \b only makes the cursor to go back one space (without erasing), so the right approach would be to emit \b \b (a backspace, a space to overwrite the character and another backspace to leave the cursor in a correct position)
The other approach is to wait to print anything until we know if the line terminates with a nonblank string or it finishes with only a \n char.
The following code counts the blank characters and manages two states to cope with that. For sure you will be able to follow the code, and I have tried to document it with comments.
#include <stdio.h>
int main()
{
int c;
int state = 0;
int nblanks = 0;
/* read chars up to EOF */
while((c = getchar()) != EOF) {
switch (state) {
case 0: /* no nonblank character read */
switch (c) {
/* accumulate number of blanks to be printed in case
* we see a nonblank char before \n */
case ' ': nblanks++; break;
/* in this case we have seen nblanks before a \n, so
* we have to print only one blank and \n */
case '\n':
puts(" "); /* just one space */
nblanks = 0; /* reset counter */
break;
/* nonblank char */
default:
/* print all the blanks up to here */
printf("%*s%c", nblanks, "", c);
state = 1; /* switch state */
break;
} /* switch */
break;
/* we have read at least a nonblank char, so we must
* echo the line until the end. */
case 1:
if (c == '\n') {
state = 0;
nblanks = 0;
} /* if */
putchar(c);
break;
} /* switch */
} /* while */
} /* main */
It's completely compatible with K&R second edition, so you only have to compile it and run.
Perhaps the most difficult statement to follow is the printf() line in the middle. The asterisk * allows me to specify the width of the field with a printf parameter, and passing an empty string "" allows me to print a string with nblanks spaces. The final %c format is to print the nonblank character just read. This leads to a compact and efficient code.
Last, some wrong ideas you have:
\b only goes back one character in the terminal (one character, not one line). I't only works when printing to a terminal or to a printer. It doesn't work on a file (the file will get the backspaces as normal characters inside)
\r makes the cursor to go to the first display column. This works only on the screen and in a printer. It does not work in a file, where it gets included as a normal character.
\0 Is a character used by C programs to finish character strings (to know where in memory they finish) It is not a special character for an output device, and it does nothing (it is the ASCII NUL character, does nothing on the output terminal)
finally, if you try to follow the \b \b approach on a printer, it will not erase anithing as the space doesn't erase what has already been printed. So then, you have to follow the second approach.

the desired algorithm should be something like:
implement a state machine with two states. NotInSpaces and InSpaces
(with just two states, a boolean would work)
no special treatment for '\n'
set state to NotInSpaces
Loop: (exit loop on EOF)
getchar
if char is space
then if state is NotInSpaces
then set state to InSpaces
output space
endif
else
output char
endif
end Loop:
output '\n' // to force output buffer flush

Related

K&R Chapter 1.5.4: "How would you test the word count program?"

Beginner here.
In the ANSI C textbook by K&R, page 20, they ask: How would you test the word count program?
I have copied exactly from the text book, using the CodeBlocks IDE, console application. I have seen many great input tests online, but my question is even dumber. How do I actually input something? Nothing happens when I press enter. Do I have this problem because I am using an IDE and therefore not learning how to run C programs properly?
Thanks in advance. I added a picture to show you what I mean
Here is the code:
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
/* counts lines, words and characters as input */
main()
{
int c, nl, nw, nc, state;
state = OUT;
/* set these three constants to 0: */
nl = nw = nc = 0;
while ((c = getchar()) != EOF){
++nc;
if (c == '\n')
++nl;
/* || == OR (&& == AND)
evaluation of the following line
will stop as soon as the truth or
falsehood is known, so the order matters */
if (c == ' ' || c == '\n' == c == '\t')
state = OUT;
else if (state == OUT){
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}
On MacOS:
gcc kr_wc.c -o kr_wc
./kr_wc < example_text.txt
Example output:
40 260 1397
Where example_text.txt is this file:
1.5.4 Word Counting
The fourth in our series of useful programs counts lines, words, and
characters, with the loose definition that a word is any sequence of
characters that does not contain a blank, tab or newline. This is a
bare-bones version of the UNIX program wc.
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
/* count lines, words, and characters in input */
int main() {
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}
Every time the program encounters the first character of a word, it
counts one more word. The variable state records whether the program
is currently in a word or not; initially it is "not in a word", which
is assigned the value OUT. We prefer the symbolic constants IN and
OUT to the literal values 1 and 0 because they make the program more
readable. In a program as tiny as this, it makes little difference,
but in larger programs, the increase in clarity is well worth the
modest extra effort to write it this way from the beginning. You'll
also find that it's easier to make extensive changes in programs
where magic numbers appear only as symbolic constants.
The program to count words in K&R 2nd edition is made to run on an environment in which you signal the end of input somehow. Normally, as they used UNIX all the time, they used Ctrl-D sequence (which is valid if you run the program in Linux or any Unix-like operating system) This has been so since the early beginning of the UNIX system.
Windows signals the end of input in a console application by the input of a Ctrl-Z (probably followed by a keyboard return key)
If you redirect the input from a file (as when you say a.out <my_input_file.txt) you'll get the number of words at the end, when there's no more input in the file.
You are running the program in an IDE, which is something that normally hides you where standard input and standard output go, or how to signal the window you show how to say that there's not more input to the program.
For the program to get to it's end, you have first to know how to get to an end on input.
The examples in K&R omit a return type of main, which is not valid in modern C, so add int before main():
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
/* counts lines, words and characters as input */
int main()
{
int c, nl, nw, nc, state;
state = OUT;
/* set these three constants to 0: */
nl = nw = nc = 0;
while ((c = getchar()) != EOF){
++nc;
if (c == '\n')
++nl;
/* || == OR (&& == AND)
evaluation of the following line
will stop as soon as the truth or
falsehood is known, so the order matters */
if (c == ' ' || c == '\n' == c == '\t')
state = OUT;
else if (state == OUT){
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}
"How do I actually input something? Nothing happens when I press enter."
If you got problems with your IDE just run it online.
"How would you test the word count program"?
To cite the authors of a bundle of K&R solutions with an answer to that particular question here:
It sounds like they are really trying to get the programmers to learn how to do a unit test. I would submit the following:
input file contains zero words
input file contains 1 enormous word without any newlines
input file contains all white space without newlines
input file contains 66000 newlines
input file contains word/{huge sequence of whitespace of different >kinds}/word
input file contains 66000 single letter words, 66 to the line
input file contains 66000 words without any newlines
input file is /usr/dict contents (or equivalent)
input file is full collection of moby words
input file is binary (e.g. its own executable)
input file is /dev/null (or equivalent)
66000 is chosen to check for integral overflow on small integer machines.

How to scanf until I get something not of the same form

I am inputting a text file from Stdin, which will have an undetermined number of coordinates, then a #, then another set of coordinates. How do I scanf the coordinates into a loop that stops once I hit the #, that will let me scanf the rest of the coordinates after the #?
I have tried a couple of loops like:
`while(scanf("[%d,%d]\n", &x, &y) == 1){
//do stuff//
}
but I dont feel like im getting any closer to an answer, any help would be greatly appreciated, cheers
input example (the # doesnt have "" around it but it disappears on here if it doenst):
[0,0]
[1,1]
[2,2]
"#"
[1,3]
[3,6]
[9,8]
You probably want to wrap the code into fgets(or readline):.
char buff[2048] ;
while ( fgets(buff, sizeof(buff), stdin )) {
// Check of 'last' marker
if ( buff[0] == '#' ) break ;
// Check if looks like coordinates
if ( sscanf(buff, "[%d,%d]\n", &x, &y) == 2 ) {
// do something
} ;
} ;
Minor fix to sscanf return code (2 instead of 1) - check for parsing of 2 fields
Your input data delimited by a double-quoted "#" complicates matters slightly. Your attempt to read with scanf is destined to fail. Your scanf format string of "[%d,%d]\n" does not read/discard the '\n' at the end of the line. In fact it doesn't match a '\n' at all. scanf does not interpret control characters, so what the '\n' in your format string is looking for is a literal 'n' leading to an input-failure after the two conversions take place.
You have two options:
remove the '\n' from your format string, continue with scanf (not recommended) and then manually read/discard all remaining characters in the line until a '\n' is reached (using either getchar() or fgetc()); or
read each line into a buffer using a line-oriented input function like fgets() or POSIX getline() to ensure a complete line of data is read each time and then parse the information you need from the buffer with sscanf (preferred method).
Taking the preferred approach above, you could do something similar to:
#include <stdio.h>
#include <string.h>
#define MAXC 1024 /* if you need a constant, #define one (or more) */
int main (void) {
char buf[MAXC]; /* buffer for each line */
int x, y, n = 0; /* coordinates & counter */
printf ("set[%d]:", n++); /* initial set[]: label */
while (fgets (buf, MAXC, stdin)) { /* read each line */
if (strncmp (buf, "\"#\"", 3) == 0) /* line starts with "#"? */
printf ("\nset[%d]:", n++); /* output new set[]: label */
else if (sscanf (buf, " [%d,%d]", &x, &y) == 2) /* 2 conversions? */
printf (" %d,%d", x, y); /* output coordinates */
}
putchar ('\n'); /* tidy up with newline */
return 0;
}
(note: if your file simply contained # instead of "#", you could simply check the first character in the buffer instead of using strncmp)
Example Input File
$ cat dat/coordgroups.txt
[0,0]
[1,1]
[2,2]
"#"
[1,3]
[3,6]
[9,8]
Example Use/Output
$ ./bin/readcoords < dat/coordgroups.txt
set[0]: 0,0 1,1 2,2
set[1]: 1,3 3,6 9,8
Look thing over and let me know if you have further questions.

Accepting a single character in C?

What I intend to do is to get the character entered and used it as a pattern. I've tried using getchar() but it won't work. I've hear of using scanf but it skips and stops whenever I press "shift" for the special characters on my keyboard.
int i, j, n;
char c;
c = getchar();
printf("Enter value of n: ");
scanf("%d", &n);
printf("Enter a Character: ");
getchar();
for(i=1; i<=n; i++)
{
for(j=1; j<=i; j++)
{
printf("%c", c);
}
printf("\n");
}
You need to assign the value returned by getchar to the variable c, and you had a redundent call to getchar that's why it skips reading the desired input:
int i, j, n;
char c;
printf("Enter value of n: ");
scanf("%d", &n);
printf("Enter a Character: ");
scanf(" %c", &c);
for(i=1; i<=n; i++)
{
for(j=1; j<=i; j++)
{
printf("%c", c);
}
printf("\n");
}
You can use %c with scanf:
scanf("%d %c", &n, %c);
This eliminates the need for the two getchar calls.
The space is required; it tells scanf to skip whitespace.
The problem you have is that your assumptions on getchar(3) are incorrect. You think getchar() is going to return the next key pressed in the input stream, but you are incorrectly assuming that it will be done without buffering or system processing (the terminal driver gives the program complete lines, or even worse, if you are reading from a file, complete buffer blocks, that have to be buffered so you miss no characters from the input stream)
You are assuming incorrectly that the end of line you need to press for the input to be feeded to the program does not count in the input stream.
What actually happens is:
you feed a complete line (because the kernel driver works that way) so you press your character, and then you see nothing, not after you have pressed the return key.
once you press it, you have more than one character (depending on how many you pressed before hitting the return key) that will stay in the buffer, until they are so consumed by the program. Normally this happens when you have executed more getchar() or scanf() statements.
The idea of this buffering mechanism is to allow a programmer to process character by charcacter large amounts of text, without the overhead of making a system call per character reading (this is a costly operation) so think of getchar() not as a sample function to get new users introduced to the world of programming, but as a hint to experienced programmers to use efficiently without having to think on buffering large amounts of text.
With stdio package, every character counts, so you have to think slowly and minuciously when you feed input to getchar(3).
The next question is: Right, then how can I solve and stop my program until I press some key? The first answer, with the set of tools you have exposed here is, be careful on what you input, instead of asking for any key, ask the user to press the return key, and then, do something like:
printf("Hit <ENTER> to continue"); fflush(stdout); /* so we get the line out, bypassing the buffering mechanism */
int c;
while ((c = getchar()) != EOF && c != '\n') {
/* just ignore the character we have received */
}
/* c == '\n' || c == EOF, so we can continue */
or, if you prefer, you can write a function just to do this (as there can be so many criteria to implement it, nobody included such a function in the standard C library, my apologies for that. ;) )
void wait_for_enter()
{
/* I use stderr, for two reasons:
* o stderr is normally unbuffered, so there's no need to fflush()
* o stdout can be redirected, so the prompt will not be visible in
* case you want to save the output of your program.
*/
fprintf(stderr, "Hit <ENTER> to continue");
int c;
while ((c = getchar()) != EOF && c != '\n') {
/* just ignore the character we have received
* until we get the end of file (ctrl-d at the terminal)
* or a new line */
}
/* c == '\n' || c == EOF, so we can continue */
/* it's assumed that the user pressed the enter key, so the echoed
* enter already did a newline, no need to do it here */
} /* wait_for_enter */
In order to wait for any character and in raw mode, you need first to ensure your input comes from a terminal (you cannot do the following on a normal file), then you have to switch the terminal driver to raw mode, so each character is given immediately to the program and no line editing processing is done, and then set the stdin descriptor to no buffering at all. Only then, you can receive individual characters with getchar(3), one by one, as they are keyed in. I think this is far out of the scope of this question, as the code to do that is far more complex than the above.
EDIT
Following is a complete sample of a program that uses raw input to process characters as they are keyed in.
/* pru.c -- program to show raw input from the terminal.
* Author: Luis Colorado <luiscoloradourcola#gmail.com>
* Date: Fri Sep 20 08:46:06 EEST 2019
* Copyright: (C) 2019 Luis Colorado. All rights reserved.
* License: BSD.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h> /* see termios(3) for a description on terminal conf */
#define F(_fmt) __FILE__":%d:%s: " _fmt, __LINE__, __func__
/* this function switches the terminal into raw mode and returns a malloc(3)ed
* terminal configuration, so it can be later restored. BEWARE that the returned
* configuration info must be deallocated by free(3) once it's not needed anymore.
* In case of failure of any system call, the function returns NULL, and errno is
* set to the failing cause. */
struct termios *set_raw(int fd)
{
struct termios *ret = malloc(sizeof *ret), cfg;
if (!ret) return NULL;
int res = tcgetattr(fd, &cfg);
if (res < 0) goto error;
*ret = cfg; /* save it for return */
cfmakeraw(&cfg);
/* set it after all buffered characters in the driver have drained out */
res = tcsetattr(fd, TCSADRAIN, &cfg);
if (res < 0) goto error;
return ret;
error:
free(ret);
return NULL;
} /* set_raw */
/* restores the configuration back to the associated file descriptor */
int restore_cfg(int fd, struct termios *cf)
{
/* set it after all buffered characters in the driver have drained out */
return tcsetattr(fd, TCSADRAIN, cf);
} /* restore_cfg */
int main()
{
struct termios *cfg = set_raw(fileno(stdin));
if (!cfg) {
fprintf(stderr, F("stdin: %s\n"),
strerror(errno));
}
setbuf(stdin, NULL); /* stdin unbuffered */
setbuf(stdout, NULL); /* stdout unbuffered */
/* BEWARE that raw mode doesn't process any characters, so no Ctrl-C(interrupt), Ctrl-D(EOF), etc.
* will be available, only if you read from a file, you'll get EOF, but you'll not be able to produce
* that on the terminal, you'll need to swith to another console and kill the process. */
int c;
while ((c = getchar()) != EOF && c != '\033') { /* ESCAPE key('\033') is a safeguard to end input */
/* print the input char as an hex number */
printf("[%02x]", c);
}
if (cfg) { /* if we were able to set the terminal to raw mode */
/* restore config */
restore_cfg(fileno(stdin), cfg);
/* and free it */
free(cfg);
}
exit(EXIT_SUCCESS);
} /* main */
The full source code can be also downloaded from here.
You can use this program to see how input keys get mapped into characters, as you'll note that when you press the enter key, the raw input is [0d] (ascii char 13, CARRY RETURN) while in normal line mode you get '\n' which is [0a] or ASCII LINE FEED, instead (you can check this if you redirect input from the pru.c text file). Also you'll see that you are unable to specify EOF from the terminal driver with Ctrl-D and that Ctrl-C does not come to help. Well, I have included a safeguard, by ending the program in case you press the ESC key, which generates an ASCII ESCAPE character (\033). This is also commented in the source code.
All of this processing is done by the kernel driver, so all unix implementations get the same line end characters or interpret the control characters the same way.

Number Pad [Enter] not \n in C?

I'm working on a small C program for a college assignment and I've noticed a weird bug in my code. I use an iMac with the short keyboard generally, but its battery was flat so i plugged in a standard USB keyboard with number pad.
The weird thing is that if I hit [Enter] on my number pad, it seems to do what the regular [Enter} key does, but the \n I am trying to detect in the stdin function I made to read the keyboard input, doesn't work when I use the number pad's [Enter] key.
Wtf?
Here is my function that reads the user input:
/* This is my implementation of a stdin "scanner" function which reads
* on a per character basis until the the termination signals are found
* and indescriminately discarding all characters in the input in excess
* of the supplied (limit) parameter. Eliminates the problem of 'left-over'
* characters 'polluting' future stdin reads.
*/
int readStdin(int limit, char *buffer)
{
char c;
int i = 0;
int read = FALSE;
while ((c = myfgetc(stdin)) != '\n' && c != '\0') {
/* if the input string buffer has already reached it maximum
limit, then abandon any other excess characters. */
if (i <= limit) {
*(buffer + i) = c;
i++;
read = TRUE;
}
}
/* clear the remaining elements of the input buffer with a null character. */
for (i = i; i < strlen(buffer); i++) {
*(buffer + i) = '\0';
}
return read;
}
/* This function used to wrap the standard fgetc so that I can inject programmable
* values into the stream to test my readStdin functions.
*/
int myfgetc (FILE *fin) {
if (fakeStdIn == NULL || *fakeStdIn == '\0')
return fgetc (fin);
return *fakeStdIn++;
}
NB: The myfgetc and the subsequent *fakeStdIn are part of a way that I can unit test my code and 'inject' items into the stdin stream programatically as someone suggested on this question: How do I write a testing function for another function that uses stdin input?.
What output do you get for this tiny test?
#include <stdio.h>
int main(int argc, char* argv[]) {
int c;
while((c=getchar()) != EOF) {
printf("%d\n", c);
}
return 0;
}
Could well be that on Mac, you are getting \r\n, not just \n.
So it turns out that it's a Mac OSX thing. I've spoken to other Mac users and they have the same problem. Never found a fix because one may simply not exist. The problem doesn't occur on Solaris machines and since that's the OS which the code will be run on, I guess it doesn't really matter.
I am going to answer this myself with the answer that its just one of those OSX "quirks" and be done with it.

Erase the current printed console line

How can I erase the current printed console line in C? I am working on a Linux system. For example -
printf("hello");
printf("bye");
I want to print bye on the same line in place of hello.
You can use VT100 escape codes. Most terminals, including xterm, are VT100 aware. For erasing a line, this is ^[[2K. In C this gives:
printf("\33[2K\r");
Some worthwhile subtleties...
\33[2K erases the entire line your cursor is currently on
\033[A moves your cursor up one line, but in the same column i.e. not to the start of the line
\r brings your cursor to the beginning of the line (r is for carriage return N.B. carriage returns do not include a newline so cursor remains on the same line) but does not erase anything
In xterm specifically, I tried the replies mentioned above and the only way I found to erase the line and start again at the beginning is the sequence (from the comment above posted by #Stephan202 as well as #vlp and #mantal) \33[2K\r
On an implementation note, to get it to work properly for example in a countdown scenario since I wasn't using a new line character '\n'
at the end of each fprintf(), so I had to fflush() the stream each time (to give you some context, I started xterm using a fork on a linux machine without redirecting stdout, I was just writing to the buffered FILE pointer fdfile with a non-blocking file descriptor I had sitting on the pseudo terminal address which in my case was /dev/pts/21):
fprintf(fdfile, "\33[2K\rT minus %d seconds...", i);
fflush(fdfile);
Note that I used both the \33[2K sequence to erase the line followed by the \r carriage return sequence to reposition the cursor at the beginning of the line. I had to fflush() after each fprintf() because I don't have a new line character at the end '\n'. The same result without needing fflush() would require the additional sequence to go up a line:
fprintf(fdfile, "\033[A\33[2K\rT minus %d seconds...\n", i);
Note that if you have something on the line immediately above the line you want to write on, it will get over-written with the first fprintf(). You would have to leave an extra line above to allow for the first movement up one line:
i = 3;
fprintf(fdfile, "\nText to keep\n");
fprintf(fdfile, "Text to erase****************************\n");
while(i > 0) { // 3 second countdown
fprintf(fdfile, "\033[A\33[2KT\rT minus %d seconds...\n", i);
i--;
sleep(1);
}
You can use a \r (carriage return) to return the cursor to the beginning of the line:
printf("hello");
printf("\rbye");
This will print bye on the same line. It won't erase the existing characters though, and because bye is shorter than hello, you will end up with byelo. To erase it you can make your new print longer to overwrite the extra characters:
printf("hello");
printf("\rbye ");
Or, first erase it with a few spaces, then print your new string:
printf("hello");
printf("\r ");
printf("\rbye");
That will print hello, then go to the beginning of the line and overwrite it with spaces, then go back to the beginning again and print bye.
You could delete the line using \b
printf("hello");
int i;
for (i=0; i<80; i++)
{
printf("\b");
}
printf("bye");
Usually when you have a '\r' at the end of the string, only carriage return is printed without any newline. If you have the following:
printf("fooooo\r");
printf("bar");
the output will be:
barooo
One thing I can suggest (maybe a workaround) is to have a NULL terminated fixed size string that is initialized to all space characters, ending in a '\r' (every time before printing), and then use strcpy to copy your string into it (without the newline), so every subsequent print will overwrite the previous string. Something like this:
char str[MAX_LENGTH];
// init str to all spaces, NULL terminated with character as '\r'
strcpy(str, my_string); // copy my_string into str
str[strlen(my_string)] = ' '; // erase null termination char
str[MAX_LENGTH - 1] = '\r';
printf(str);
You can do error checking so that my_string is always atleast one less in length than str, but you get the basic idea.
i iterates through char array words. j keeps track of word length. "\b \b" erases word while backing over line.
#include<stdio.h>
int main()
{
int i = 0, j = 0;
char words[] = "Hello Bye";
while(words[i]!='\0')
{
if(words[i] != ' ') {
printf("%c", words[i]);
fflush(stdout);
}
else {
//system("ping -n 1 127.0.0.1>NUL"); //For Microsoft OS
system("sleep 0.25");
while(j-->0) {
printf("\b \b");
}
}
i++;
j++;
}
printf("\n");
return 0;
}
This script is hardcoded for your example.
#include <stdio.h>
int main ()
{
//write some input
fputs("hello\n",stdout);
//wait one second to change line above
sleep(1);
//remove line
fputs("\033[A\033[2K",stdout);
rewind(stdout);
//write new line
fputs("bye\n",stdout);
return 0;
}
Click here for source.
under windows 10 one can use VT100 style by activating the VT100 mode in the current console to use escape sequences as follow :
#include <windows.h>
#include <iostream>
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#define DISABLE_NEWLINE_AUTO_RETURN 0x0008
int main(){
// enabling VT100 style in current console
DWORD l_mode;
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleMode(hStdout,&l_mode)
SetConsoleMode( hStdout, l_mode |
ENABLE_VIRTUAL_TERMINAL_PROCESSING |
DISABLE_NEWLINE_AUTO_RETURN );
// create a waiting loop with changing text every seconds
while(true) {
// erase current line and go to line begining
std::cout << "\x1B[2K\r";
std::cout << "wait a second .";
Sleep(1);
std::cout << "\x1B[2K\r";
std::cout << "wait a second ..";
Sleep(1);
std::cout << "\x1B[2K\r";
std::cout << "wait a second ...";
Sleep(1);
std::cout << "\x1B[2K\r";
std::cout << "wait a second ....";
}
}
see following link : windows VT100
there is a simple trick you can work here but it need preparation before you print, you have to put what ever you wants to print in a variable and then print so you will know the length to remove the string.here is an example.
#include <iostream>
#include <string> //actually this thing is not nessasory in tdm-gcc
using namespace std;
int main(){
//create string variable
string str="Starting count";
//loop for printing numbers
for(int i =0;i<=50000;i++){
//get previous string length and clear it from screen with backspace charactor
cout << string(str.length(),'\b');
//create string line
str="Starting count " +to_string(i);
//print the new line in same spot
cout <<str ;
}
}
Just found this old thread, looking for some kind of escape sequence to blank the actual line.
It's quite funny no one came to the idea (or I have missed it) that printf returns the number of characters written. So just print '\r' + as many blank characters as printf returned and you will exactly blank the previuosly written text.
int BlankBytes(int Bytes)
{
char strBlankStr[16];
sprintf(strBlankStr, "\r%%%is\r", Bytes);
printf(strBlankStr,"");
return 0;
}
int main(void)
{
int iBytesWritten;
double lfSomeDouble = 150.0;
iBytesWritten = printf("test text %lf", lfSomeDouble);
BlankBytes(iBytesWritten);
return 0;
}
As I cant use VT100, it seems I have to stick with that solution
echo -e "hello\c" ;sleep 1 ; echo -e "\rbye "
What the above command will do :
It will print hello and the cursor will remain at "o" (using \c)
Then it will wait for 1 sec (sleep 1)
Then it will replace hello with bye.(using \r)
NOTE : Using ";", We can run multiple command in a single go.
For me, this code, work well for serial console window with arduino
on Tera Term VT console:
SEROUT.print("\e[A\r\n\e[2K");
SEROUT.print('>');
I use '>' because on my console command i type command after '>'
use this function to clear n lines in C++
void clear_line(int n) {
std::string line_up = "\x1b[A";
std::string line_clear = "\33[2K\r";
for (int i = 0; i < n; ++i)
std::cout << line_up << line_clear << std::flush;
}
Others have already answered OP's question. Here is an answer for those wondering why carriage return behaves the way it does on their Linux machine -
The behavior of the carriage return character seems to be platform-dependent.
From section '5.2.2 Character display semantics' of the C11 standard:
\r (carriage return) Moves the active position to the initial position
of the current line.
From section '3.86 Carriage-Return Character (< carriage-return>)' of the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html):
A character that in the output stream indicates that printing should
start at the beginning of the same physical line in which the
carriage-return occurred. It is the character designated by '\r' in
the C language. It is unspecified whether this character is the exact
sequence transmitted to an output device by the system to accomplish
the movement to the beginning of the line.
It does not state whether carriage return is supposed to erase (=> populate with NUL characters) the entire line or not. My guess is that it is NOT supposed to erase.
However, on my Linux machine (tried on both x86_64 and ARM32), what I observed is that the carriage return character moved the cursor to the beginning of the current line and also populated the line with '\0' characters (NUL characters). In order to notice those NUL characters, you might have to call the write system call directly from your code instead of calling via glibc printf.
Let's take the following code snippet as an example:
printf("hello");
printf("\rbye");
Building and running this on beaglebone black (32-bit ARM) bash terminal:
ubuntu#arm:~$ ./a.out
byeubuntu#arm:~$
strace output on write syscall:
bye) = 9 9hello
+++ exited with 4 +++

Resources