Reputation: 13
I was given a project where the user has to insert characters with some restrictions, but that is not the problem.
The problem is when the user presses "BACKSPACE" it should delete the last character stored in the array, but in my case it doesn't delete, it comes back so the user can replace it and that's not the goal here.
My code:
#include<stdio.h>
#include <string.h>
#include <locale.h>
main(){
int size = 0;
int pos = 0;
int var;
printf("Enter how many letters you want to write:");
scanf("%d", &size);
char text[size];
printf("Enter the characters:\n");
do{
var = getche();
if((var >= 65) && (var <= 90) || (var >= 192) && (var <= 221) || (var == 32)){
text[pos] = (char) var;
text[pos+1] = 0;
pos++;
}
else if (var == 8){
if (pos > 0){
text[pos] = 0;
text[pos] += " ";
pos--;
}
else{printf("Error");}
}
else{
text[pos] = 0;
system("cls");
printf("Enter the characters: \n");
printf("%s", text);
}
}while (pos< size);
printf("\n\nFinal string : ");
printf("%s", text);
}
All the help is much apreciated.
Upvotes: 0
Views: 92
Reputation: 58
You have to clear the output and print again the new text when you the getche gets a backspace. The code below performs what you are asking for, further improvement can be done, I'll leave that to you.
#include<stdio.h>
#include <string.h>
#include <locale.h>
int main(){
int size = 0;
int pos = 0;
int var;
printf("Enter how many letters you want to write:");
scanf("%d", &size);
char text[size];
printf("Enter the characters:\n");
do{
var = getche();
if((var >= 65) && (var <= 90) || (var >= 192) && (var <= 221) || (var == 32)){
text[pos] = (char) var;
text[pos+1] = 0;
pos++;
}
else if (var == 8){
if (pos > 0){
pos--;
text[pos] = 0;
system("cls");
printf("Enter the characters: \n");
printf("%s", text);
}
else{printf("Error");}
}
else{
text[pos] = 0;
system("cls");
printf("Enter the characters: \n");
printf("%s", text);
}
}while (pos< size);
printf("\n\nFinal string : ");
printf("%s", text);
}
Upvotes: 1