When i press a esc key it doesn't work because the cursor is on the name variable. any clue to solve that?
Why press an esc key it doesn't work probably is that scanf() function is blocking. What you can try to read characters one by one, check if the ESC key was pressed, and then build the input string from these characters.
#include <stdio.h>
#include <conio.h>
int main() {
char name[100];
int i = 0;
printf("(press esc to exit)\n");
printf("Enter Your Name: ");
while (1) {
if (_kbhit()) {
char c = _getch();
// Check for ESC key
if (c == 27) {
printf("\nExit\n");
break;
}
// Handle backspace (if needed)
if (c == 8 && i > 0) {
printf("\b \b"); // Move cursor back, print space, move back again
i--;
} else if (c == '\r' || c == '\n') { // Check for Enter key to finish input
name[i] = '\0';
printf("\nYou entered: %s\n", name);
break;
} else if (i < sizeof(name) - 1) {
name[i++] = c;
}
}
}
return 0;
}