help

Help how to trap letters in Enter your choice,How many items do you want to avail,Cash,Change.

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
#include<stdio.h>
#include<conio.h>
main()
{
int product,product1,subtract;
clrscr();
printf("1=laptop 16000");
printf("\nEnter your choice:");
	scanf("%d",&product);
	{
	clrscr();
	}
	switch(product)
	{
	case 1:
	printf("\n[$16000 Laptop]");
	printf("\nHow many items do you want to avail:");
	scanf("%d",&product);
	product1=product*16000;
	printf("%d",product1);
	printf("\nCash:");
	scanf("%d",&product);
	subtract=product-product1;
	printf("Change:%d",subtract);
	break;


getch();
}
What exactly the problem here? If you want user to input letters, do something like:
1
2
3
4
5
6
char selection;
scanf(%c, selection);
switch(selection {
case 'a'://...
caase 'b'://...
//...) 


And where is C++ in your code? All I see is plain old C
Last edited on
i want to trap the letter
example:
when i enter a leter it must be invalid input
input
Enter your choice:qweqwe
output
Invalid input
that is the problem
Last edited on
did you try the default case?
1
2
3
4
5
switch(product) {
    case 1://...
    //...
    default://Wrong input
}

Well scanf() is VERY sensitive to wrong inputs. Usually if you want to catch errors you should just read whole string and then manually parse it. If you want safe input operations - use c++ streams.
Last edited on
ok i will try
You would be better advised to drop the C style code and avail yourself of C++:

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
#include <iostream>

using namespace std;

int main()
{
	system("cls");

	cout << "1=laptop 16000" << endl;
	cout << "Enter your choice: ";
	
	char ch[2];
	ch[0] = getchar();

	if (isdigit(ch[0]))
	{
		int choice = atoi(ch), items;
		
		system("cls");

		switch (choice)
		{
			case 1:
				cout << "[$16000 Laptop]" << endl
						<< "How many items do you want to avail: ";
				cin >> items;
				int totalcost = items * 16000;
				cout << "Total cost for that is: " << totalcost << endl
						<< "How much cash?: ";
				int cash;
				cin >> cash;

				if (cash >= totalcost)
				{
					int change = cash - totalcost;
					cout << endl << "Change: " << change;
				}
				else
				{
					cout << "That isn't enough, sorry" << endl;
				}

				break;
		}
	}

	cout << endl << endl;
	system("pause");
	return 0;
}
the How many items do you want to avail,Cash,Change. how to trap the letter .
the How many items do you want to avail,Cash,Change. how to trap the letter


well I did that with the code:

 
if (isdigit(ch[0]))


If you want to do it for the other input, you can see how to do it. A seperate function to acheive that might be advisable if you are repeatedly using it.
Last edited on
Topic archived. No new replies allowed.