I am writing a basic C program which takes a word from the user as input and prints that word twice on the same row. The issue that I am facing in printing the word twice is mentioned after the code that I have written below to do this job
void print_word()
{
char ch;
char str[15];
int i = 0; /* i will be used as index to access the elements of str */
printf ("\n Enter a word of your choice : ") ;
ch = getch() ; /* Dont echo character */
while ( !isspace(ch) && i < 14) /* while loop executes till user doesn't input a space or until the str array is full */
/* isspace() is defined in header file <ctype.h> */
{
putchar(ch); /* Now echo character */
str[i] = ch ;
i++ ;
ch = getch();
} //while loop ends
str[i] = '\0' ;
printf("\t") ; //print a gap
printf ("%s ", str) ;
printf ("%s", str) ;
}
This function works properly if user directly enters a word (without using backspace to edit the word).
Suppose user enters 'HELLO' then 5 characters viz.'H' 'E' 'L' 'L' 'O' gets stored in array str. But then user presses backspace three times and the word on the console appears 'HE' while str now contains eight characters H-E-L-L-O and 3 backspace characters. But when the printf function in the last two statements of this code is executed and prints str, the first statement correctly prints the 8 character and displays 'HE' on the console, but second statement prints 'HELLO', leaving the 3 backspace characters that are also there in the array str.
Why the last printf()
statement is not printing the string str properly i.e., why is it not printing the backspace characters?
The problem remains even if I print str with puts()
function or even if the str is printed with a for loop -- character by character. And I want to know what is actually happening in the backend process?