/ Published in: C
                    
                                        
Windows console string input allowing use of left and right arrow keys, backspace, and delete. For portability, falls back to stdio functions when you define NOCONIO.
                
                            
                                Expand |
                                Embed | Plain Text
                            
                        
                        Copy this code and paste it in your HTML
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* using sleep function in windoze */
#include <windows.h>
#define yieldcpu() Sleep(0)
/* Works when using deprecated stdlib _sleep */
/* quit = 1 when user presses escape key */
unsigned char quit=0;
/* this is the buffer for input */
#define maxbuf 256
char buf[maxbuf];
/* what happened to cputs? */
#define cputs(a) printf(a)
#ifndef NOCONIO
#include <conio.h>
void repeatchar(char c,int n){
while(n--)putch(c);
}
void newline(){
putch('\r');
putch('\n');
}
unsigned short getkey(){
unsigned char c;
while(!kbhit())yieldcpu();
if(c==27)quit=1;
if(c==224)return 256+getkey();
return c;
}
void pause(){
cputs("Press any key");
getkey();
newline();
}
void getstring(){
unsigned short c;
unsigned char ox=0;
unsigned char x=0;
unsigned char h=0;
while(!quit){
buf[h]=0;
putch('\r');//use gotox instead if you want something before input
cputs(buf);
putch(' ');
repeatchar(8,h-x+1);//using instead of gotox(x), puts cursor at correct position
c=getkey();
if(quit)break;
switch(c){
default:
if(h>=maxbuf-1)continue;
if(x<h){
++h;
}
buf[x]=c;
++x;
if(x>h)h=x;
continue;
case 8://backspace
if(x){
ox=x;
--x;
Del:
if(x<h){
--h;
}
}
continue;
case 339://delete key
ox=x+1;
goto Del;
case 331://left arrow
if(x){
--x;
}
continue;
case 333://right arrow
if(x<h){
++x;
}
continue;
case 327://home
x=0;
continue;
case 335://end
x=h;
continue;
case 13://enter
newline();
return;
}
}
}
#else
void newline(){
}
void getstring(){
}
void pause(){
}
#endif
/* demo program */
int main(){
newline();
getstring();
newline();
pause();
return 0;
}
Comments
 Subscribe to comments
                    Subscribe to comments
                
                