nest if-else - int but still accepting characters or enter

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  #include <stdio.h>

int main()
{
	int speed;
	
	printf("Please enter the speed: ");
	scanf("%d%*c", &speed);
	
	if (speed >= 80)
		printf("$500 fine.\n");
	else
	
		if (speed >= 70)
			printf("$150 fine.\n");
		else
		
			if (speed >= 66)
				printf("$80 fine.\n");
			else
			
				if (speed >= 60)
					printf("warning\n");
				else
	
					if (speed >= 0)
					printf("not speeding. \n");
					else
						printf("Invalid number");
	
	return(0);
}
'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.

Hopefully you will gain something from it :)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#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.
		}
		else if (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)
		}
	}
}
thanks guys..awesome..
Your welcome :)
Topic archived. No new replies allowed.