2

I want the output of the following code as

-|-2-|-

(When i input the value of key as 2). I know \b just move the cursor to 1 space back but why it isn't able to move one space back after a newline is used to input the value of key. Is it possible to use the escape character \b after a newline character has been used.

#include<stdio.h>
#include<conio.h>

int main()
{
    int key;
    printf("Enter value of key: )"
    printf("-|-");
    scanf("%d",&key);
    printf("\b-|-");
    return 0;
}
APan
  • 364
  • 1
  • 10

3 Answers3

4

Here is a simple solution :

#include<stdio.h>

int main()
{
   int key;
   char output[8] = {'\0'};

   printf("Enter value of key: )";
   scanf("%d",&key);
   sprintf(output,"-|-%d-|-",key);
   printf("%s\r\n",output);

   return 0;
}
Joze
  • 1,285
  • 4
  • 19
  • 33
  • 2
    Any reason for including the non-standard `conio.h`? – ComicSansMS Oct 07 '13 at 08:15
  • No you're right (just copy and paste his original code), I removed it. – Joze Oct 07 '13 at 08:23
  • @Joze Yes it worked but is there any way so that we -|-2-|- is shown only once on the screen.... – APan Oct 07 '13 at 08:46
  • @AdarshPanicker Could you clarify what you are asking? Right now Jose's code only outputs -|-2-|- once – sukhvir Oct 07 '13 at 09:33
  • 1
    @AdarshPanicker There is no standard function to get user input without echo. But there is no standard function like getch() which should do the job... It will depend of your OS and compiler. – Joze Oct 07 '13 at 09:35
  • @sukhvir I suppose he doesn't want the echo of the '2' – Joze Oct 07 '13 at 09:36
  • Ahh i get it .. that depends on what OS you are using . Not all systems support `getch()`. You could modify your terminal using `stty` command to make `getchar()` to that but only on linux – sukhvir Oct 07 '13 at 09:46
3

This is an easier way to achieve the same result:

#include<stdio.h>


int main()
{
   int key;
   char buffer[whatever_size];
   printf("Enter value of key: ");

   scanf("%d",&key);
   sprintf(buffer,"-|-%d-|-",key);

   printf("%s\n",buffer);
   return 0;
}
sukhvir
  • 5,265
  • 6
  • 41
  • 43
3

The terminal you are using as an output device does not have any concept of lines of text: all it knows about is a grid of cells, each of which can be filled by a character. One of the cell positions is the current cell.

The terminal interprets the BS character as an instruction to move the current cell one one column to the left. But what happens if you are already in the first column? The terminal doesn't know where the previous line ended, so it can't go back to the end of the line. It could go back to the last column of the row above, and some terminals can probably be configured to do that, but that's not likely what you want.

This is overly simplified, but it's basically why \b won't delete a line break.

Joni
  • 108,737
  • 14
  • 143
  • 193