verifying that input is hex

I need a way to make sure that input (4 digits) is in hex format. As long as you input hex, everything works fine, but if you enter a q or s or something it blows up.
The input is stored as an unsigned short int (required), so I can't store them as a string and then loop through and use isxdigit().
Thanks
Last edited on
How exactly are you storing the input as an unsigned short if it is supposed to be hex? As far as I know 0xffff isn't valid for unsigned short ints.
I Just used:
cin >> hex >> variable_name
to input the hex digits into an unsigned short.
It will end up being an interactive disassembler for a little simulator called H1 that came with our book(Assembly language and computer architecture using C++ and Java). It has a limited instruction set.
All we have to do in this first assignment is prompt for a machine instruction and then display the disassembled instruction, like this:
?4000
Op Code:4 Address field:000

?1e25
Op Code:1 Address field:e25

?ffff
Op Code:ffff Address field:

Most H1 instructions use a 4bit(single hex digit)op-code and a 12 bit(3 hex digit)address field. Next week we will probably have to add the ones that use 8 and 12 bit instructions, but for this assignment all we had to concern ourselves with one exception (ffff-HALT).
Here is the whole thing. Using structs and a union were a requirement. It works perfectly as long as the input is a 4 digit valid hex number.

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

int main( )
{
	
	//structures for both one hex character
	//and two hex character instructions
	struct single_byte_inst
	{
		unsigned short int addr:12;
		unsigned short int inst:4;
	};
	struct doub_byte_inst
	{
		unsigned short int addr:8;
		unsigned short int inst:8;
	};
	
	union machine_code
	{
		unsigned short int input;
		single_byte_inst single;
		doub_byte_inst doub;
	
	};
	machine_code x;
	system("cls");
	cout <<"Enter machine code(in hex format), -1 to quit:"<<endl;
	cout << endl << "?: ";
	cin >> hex >> x.input;
	//loop until input is -1
	while (x.input!=-1)
	{
		//check for halt instruction
		if (x.input == 0xffff)
			cout << "Op Code: ffff" << "    Address field: " << endl;
		else
		{
			cout << endl;
			cout << "Op Code: " << hex << setfill('0');
			cout << x.single.inst << "  " ;
			cout << "Address field: " << hex << setw(3)<< x.single.addr << endl;
		}	
		cout << endl;
		cout << "? ";
		cin >> hex >> x.input ;
	}
	cout << "Good bye!"<<endl;
Last edited on
It's probably the same problem as if you cin >> an int and you input characters. Use:

if(!(cin >> /*...*/)) to check if it worked.
Topic archived. No new replies allowed.