Virtual Machine!

how can I change this program to read commands from a file and execute 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
54
55
56
57
58
59
60
61
62
63
64
65
  #include <iostream>
using namespace std;

//    INSTRUCTION SET
//     mnemonic = machine code;  action
const int CLR = 0;   // acc = 0
const int ADD = 1;   // acc = acc + num
const int MUL = 2;   // acc = acc * num
const int OUT = 3;   // cout << acc
const int HALT = 4;  // stop CPU

int ram[] = {
	CLR,     // clear register 
	ADD, 5,  // add 5 to accumulator
	MUL, 4,  // add 4 to accumulator
	OUT,     // display answer from accumulator      
	HALT };  // stop the machine

// the CPU 
int opcode, operand;  // hold our instruction and data
int step = 0;         // keep track of RAM
int acc = 0;          // main register, often called the ACCumulator


void execute(int opcode)
{
	switch (opcode) {
	case CLR:
		acc = 0;
		step++;    // ready for next instruction
		break;
	case ADD:
		operand = ram[++step];
		acc += operand;
		step++;    // ready for next instruction
		break;
	case MUL:
		operand = ram[++step];
		acc *= operand;
		step++;    // ready for next instruction
		break;
	case OUT:
		cout << acc;
		step++;    // ready for next instruction
		break;
	}
}




int main()
{
	cout << "Simple Virtual CPU " << endl;

	do {  // CPU's fetch execute cycle
		opcode = ram[step];         // fetch 
		execute(opcode);            // execute 
	} while (opcode != HALT);

	cout << "\n\n shutting down \n\n";

	return 0;
}
Topic archived. No new replies allowed.