If I enter "a", its shows 500 instead "invalid data"
or if I press enter, it keeps jumping lines
why does it happens??
what is the right code?? if its wrong.
'a' converted to an integer is 97, so that makes sense. If you press enter by itself, it gets treated funky. It's hard to explain, but you need to do some extra error handling specifically for those situations, but IMHO, it's not worth it.
You could write a function to get the key strokes using _getch(), I have provided an example of what I mean below. Probibly not perfect for what you want to achieve but it serves as an example for you.
#include <stdio.h>
#include <conio.h> // for getch
#include <stdlib.h> // for atoi
int getSpeed(); // function declaration
int main()
{
int speed;
speed = getSpeed(); // run the function
// speed now has what was returned from the function,
// display it.
printf("\nI got a %d\n", speed);
}
//
// $function: getSpeed()
// $purpose: Read the keyboard only allowing characters 0 - 9 and the delete key
// $date: 12/03/2014
//
int getSpeed()
{
char ch;
char speed[2];
int count = 0;
printf("Enter speed: ");
// endless loop which will exit when I have typed 2 digits.
for (;;){
ch = _getch();
if (ch >= '0' && ch <= '9') // only accept 0 - 9
{
speed[count] = ch; // its valid, store it
count++; // update array index.
printf("%c", ch); // show what i typed to screen
if (count > 1) // have i got my two digits (remember array first index is 0)
return(atoi(speed)); // convert the array to a integer and return it.
}
elseif (ch == 8) { // if I wasnt 0-9, was I a backspace?
// yes i was, reset index back to zero
count = 0;
printf("%c ", ch); // do the backspace (with an extra space to clear what was typed)
}
}
}