how to call specific functions via keyboard input in simple c++ program

Hi all,

I've written a simple 'Hello World' C++ program.

I have also written a simple 'Hello User' C++ program (Identical to the 'Hello World' program apart from the cout text output.

How could I write this program to first ask the user to press the '1' keyboard key to see the 'Hello World' output, and the '2' keyboard key to see the 'Hello User' output?

One way to do it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

int main(int argc, char **argv)
{
  cout << "Press 1 to see Hello world or press 2 to see Hello user. ";

  char ch;
  if(cin.get(ch))
  {
    if (ch == '1')
      cout << "Hello world.\n\n";
    else if (ch == '2')
      cout << "Hello User\n\n";
  }    
  system("PAUSE");

  return 0;
}
#include <iostream>

using namespace std;

int main()
{
int num;
cout << "Press 1 to see Hello world or press 2 to see Hello user. "<<endl;
cin>>num;

if(num==1)
{
cout<<"Hello world "<<endl;
}
else if (num == 2)
{
cout << "Hello User\n";
}
else
{
cout<<"erore"<<endl;
}


return 0;
}




in the above example, is it possible to define a cin variable that will accept a text word-command (such as 'help' or 'info') instead of just a single integer?

How would I do that?

Here's my (working) code. I want to replace the option for '5' and '6' with 'info' and 'exit'.

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
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <string>

using namespace std;


int main()
{
	
	// holds the value of the user's input.
	int num;
	
	// arbitrary value of variable 'beans'.
	int beans = 1000;

	// arbitrary value of variable 'rice'.
	int rice = 800;

	List:
	cout << "Press 1 to see the number of beans." << endl;
	cout << "Press 2 to see the amount of rice." << endl;
	cout << "Press 3 to see the Memory Address of the beans value" << endl;
	cout << "Press 4 to see the Memory Address of the rice value." << endl;
	cout << "Press 5 to see this list again." << endl;
	cout << "Press 6 to end the program." << endl;
	
    StartOver:
	
	
	cin >> num;
	
	if (num == 1)
	{
		cout << beans << endl;
		goto StartOver;
	}
	if (num == 2)
	{
		cout << rice << endl;
		goto StartOver;
	}
	if (num == 3)

	{
		cout << &beans << endl;
		goto StartOver;
	}
	if (num == 4)
	
	{
		cout << &rice << endl;
		goto StartOver;
	}
	if (num == 5)
	{
		goto List;
	}
	
	if (num == 6)
	{
		goto exit;
	}
	
	else
	{	
		cout << "Your input was not on the list. Please try again." << endl;
	goto StartOver;
	}

	exit:
	
	return 0;
}
Last edited on
Topic archived. No new replies allowed.