0

I'm developing a program that uses malloc and realloc functions to increment the pointer buffer in real-time while the user is typing a string.

The problem is, that I'd like to prevent the user from hitting Backspace to correct the input. Is it possible to block Blackspace key somehow in C while using getche()?

My final program will have two inputs: one without Backspace (you can't go back), and another with Backspace. (you can correct the input and then press Enter).

char *szString;
char *tmp;
int i = 0;
char c;

szString = '\0';
szString = malloc(1);

printf("Enter a string: ");

while ((c = getche()) != '\r')
{
    if(c = 0x08) // BackSpace
    {
        //
    }
    szString[i] = c;
    i++;
    tmp = realloc(szString, i+1);
    szString = tmp;
}

szString[i] = '\0';

printf("\nYou typed: %s", szString);
user2729661
  • 9
  • 1
  • 1
  • 6
  • 1
    `szString = '\0';` should give you an integer-to-pointer warning & and the `malloc` on the next line makes it redundant... – Kninnug Dec 02 '13 at 16:51

4 Answers4

1

The following is a crude implementation of a function that return -1 if backspace else the charatcer itself

char read_all_except_backspace()
{
    char ch;
    system("stty raw");
    ch = getchar();
    system("stty cooked");
    if(ch == 127)
        //value of backspace in my unix implementation is 127,i doubt it :-/
        return -1;
   else
      return ch;
}   

If on windows you can use getch instead of the above function.Ignore the input if read character is backspace.You can find the value of backspace by printing it as an integer.

The above can be achieved on a windows system by something like this.

char ch=0,str[100];
int i=0;
while(ch!=10)//enter pressed
{
    ch = getch();
    if(ch == 127)
        continue;
    str[i++]=ch;
}
str[i-1]=0;
rjv
  • 6,058
  • 5
  • 27
  • 49
1

New answer: OK, then I would update the code to print the last character of the string (again) to advance the cursor to the position before the backspace (and jump over the rest of the code).

Original answer: Why not just use getch() instead and print and process the character - unless it is a backspace!

Andrew Rump
  • 133
  • 1
  • 1
  • 10
0

The getche() function automatically echoes the character read to the screen. If you want backspace to "not delete" characters already entered, you will have to re-echo (re-print) the last character entered before the backspace so that it "appears like" the backspace key was not registered.

Joy Rê
  • 159
  • 4
0

yes, just check that user is pressing backspace or not, if backspace is detected then just ignore don't increase value of subscripted variable and use continue or put your code inside if else block and just skip the backspace part

asifaftab87
  • 1,315
  • 24
  • 28