How can I make the function return to the for loop

Can somebody show me how I can make the function randomNumber quit by pressing the 2 key instead of having to use ctrl+z? thanks.

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
  #include <ctime>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>

enum BOOL {FALSE,TRUE};
typedef unsigned short USHORT;

void randomNumber();
USHORT menu();

int main()
{
	BOOL exit = FALSE;
	for (;;)
	{
		USHORT choice = menu();
		switch(choice)
		{
			case (1):
			randomNumber();
			break;
			case (2):
			exit=TRUE;
			break;
			default:
			std::cout<<"Please select again!\n";
		}
		if(exit)
		break;
	}
}

USHORT menu()
{
	USHORT choice;
	
	std::cout<<"  *** Menu *** \n\n";
	std::cout<<"(1)Stream of random numbers!\n";
	std::cout<<"(2)Quit!\n";
	
	std::cin>> choice;
	return choice;
}

void randomNumber()
{
	while(1)
	{
	srand (static_cast <unsigned> (time(0)));
    float r = static_cast <float> (rand() / static_cast <float> (RAND_MAX));
	printf("This is the random number: %f\n",r);
	}
}
 

only call srand once unless you want the same stream multiple times (there are use cases for that). Calling it in the loop is pointless.

the function has while(1) and no way out. If you want it to stop, give it a way to do so, for example:
srand(time(0);
for(int i = 0; i < 10; i++)
cout << rand() << endl;

or whatever you want to do.
c++ does not have a keypressed type function but libraries do, so if you want a while not keypressed or while keypressed not equal '2' then you need a library to do it, or a fair bit of work and know how to do it yourself (embed assembly, or tap into the device buffer). You can also do it with threads.
Last edited on
C++ has bool type built-in. You don't need to use an enum.

But anyway... your randomNumber function consistes of an infinite where you keep re-seeding the RNG and then calling and printing the random number.

Your main function already has a loop in it, and entering 2 should cause you to break out of it. What do you want randomNumber to do? Generate a single random number? If so, remove the while(1) loop.

Also, you only should seed rand once. Put line 51 (the srand call) at the beginning of main.

Edit: If your goal is to randomly generate and print numbers as fast as possible until the user presses 2 in real-time, then you want what jonnin is talking about. What platform are you programming on?
For Windows, look up "async key press", for example: https://stackoverflow.com/questions/8640208/what-is-the-fastest-way-to-determine-a-key-press-and-key-holding-in-win32
Last edited on
Topic archived. No new replies allowed.