Pointer: pointing to choice in switch statement

How would I 'point' (deference) a pointer to something that was selected in a switch statement? I created a pointer and a switch statement. The user selects a choice. How do I make the pointer point to what was selected? No, I don't want an easier way of doing this, I want to know how I would do it with a pointer. Here is what I have so far:

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
#include <iostream>
using namespace std;

void main()
{
	int a=0, b=0, c=0, d=0, e=0, pt=0;
	int *number;

	cout << "Enter number 1: " << endl;
	cin >> a;
	cout << "Enter number 2: " << endl;
	cin >> b;
	cout << "Enter number 3: " << endl;
	cin >> c;
	cout << "Enter number 4: " << endl;
	cin >> d;
	cout << "Enter number 5: " << endl;
	cin >> e;
	cout << "Enter number to point to: " << endl;
	cin >> pt;
	switch(pt)
	{
	case '1':
		number = &a;
		break;
	case '2':
		number = &b;
		break;
	case '3':
		number = &c;
		break;
	case '4':
		number = &d;
		break;
	case '5':
		number = &e;
		break;
	}
	cout >> *number;
}


I got a ton of errors in this program.
seems like the only problems are your cases, '1' means character 1, just use 1. case 1:
To be safe, always make case '5' into default
cout >> *number; //error - arrows pointing wrong way
I see only two errors.
The first. Instead of

void main()

you shall write

int main()


The second. Instead of

cout >> *number;

you shall write

cout << *number;

As for your question you could use an array of the type int

1
2
3
4
5
6
7
8
9
10
const size_t N = 5;
int a[N];

// here you fill the array

cout << "Enter number to point to: " << endl;
cin >> pt;

if ( 0 < pt && pt < 6 ) std::cout << a[pt-1] << std::endl;
else std::cout << "you have enetered incorrect number\n";
It worked, thanks everyone. Can't believe I missed the "cout <<" at the end.
I'm a fan of unsigned.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

void main()
{
	int a[5];
	unsigned pt;

	for (unsigned i = 0; i < 5; ++i) {
		cout << "Enter number " << i + 1 << ": " << endl;
		cin >> a[i];
	}
	
	cout << "Enter number to point to: " << endl;
	cin >> pt--;
	
	if (pt < 5) cout << a[pt];
}
Last edited on
Topic archived. No new replies allowed.