backspace problem with scanf
Hello all,
I have written a Linux application program which tests the various peripherals on-board runs on ARM Board. This menu driven application takes input from scanf as code snippet below printf("Enter Your Choice :"); scanf("%s",&c); i = atoi(&c); switch (i) { case 1: while(1){ //test one } case 2: break; - - - case 14: break; } when I execute on this and try for back space it gives some garbage as -------------------------- 13.Automatic Test 14.Exit Enter Your Choice :fffffff --------------------------- Anyone guide on this ? |
First of all; enclose your code with [ code ] tags. It makes it much more readable for the rest of us.
Then; I think your issue is with atoi actually; I don't think atoi can translate backspace to integer :-) Since a char is easily also an small integer form (don't shoot me on this, but I recall it as an 8-bit integer, containing the values 0-255); you could -of course- instead do switch(c) instead... only with different values; you'd have to figure out what values correspond to which number. |
It looks like you defined c as a single character but scanf is expecting a character array.
|
I think you cannot catch backspace that way. You need to read keycodes before they will be evaluated
http://www.linuxquestions.org/questi...d-in-c-150067/ |
Quote:
|
Quote:
|
As I wrote you you cannot solve it that way. You need to catch all the keys pressed and act on that (so handle backspace, print letters ...). scanf just reads the keyboard buffer (more or less) which contains the keys pressed one by one.
|
Quote:
Quote:
Even if you are only interested in the first character in the array, having only just enough room for two characters (plus the null) in the character array is just begging for a segfault if the user types more than 3 characters. |
Quote:
Code:
char c[10]; |
incomplete.
And what is the problem, exactly? What's happening, when you press <BkSpc] key? |
Quote:
|
Quote:
Quote:
|
Terminal-drivers are usually able to handle backspace key (you have to use stty(1) or termios(2) to prevent this), for example pressing keys 1 2 4 BkSpc 3 Enter should result "123" in varible 'c'
|
Quote:
Code:
char c[10]; Enter your choice:123backspace should be 12 but prints invalid option as defined at default switch case. |
Quote:
Any example code |
All times are GMT -5. The time now is 11:25 PM. |