Message Box

I want the message box to display a random number, here is what I have:

1
2
3
4
5
6
7
8
9
10
11
#include <time.h>
#include <windows.h>

int main(void)
{
    using namespace std;
    srand(time(NULL));
    int i = rand() % 2 + 1;
    MessageBox (NULL, i, "Result", MB_OK);
    return main();
}


and I get an error :( any help? Thanks
Replace return main(); with return 0;.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <ctime>
#include <cstdlib>
#include <windows.h>

int main()
{
    srand(time(0));

    int i = rand() % 2 + 1;

    char buffer[5];
    itoa(i,buffer,10);

    MessageBox (0, buffer, "Result", MB_OK);

    return 0;
}

http://cplusplus.com/reference/clibrary/cstdlib/itoa/
Last edited on
pabloist, return 0 makes the program close once it hits that, I wanted it to return to main and open another message box when I closed the current one.

m4ster r0shi, thank you this helps
TheEliteOne wrote:
I wanted it to return to main and open another message box when I closed the current one.

It's better to do it using a loop:

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

int main()
{
    srand(time(0));

    std::cout << "hold esc to quit..." << std::endl;

    while(true)
    {
        int i = rand() % 2 + 1;

        char buffer[5];
        itoa(i,buffer,10);

        MessageBox (0, buffer, "Result", MB_OK);

        if (GetAsyncKeyState(VK_ESCAPE)>>15) break;
    }

    return 0;
}

EDIT: Oh, and to avoid calling itoa all the time, you can do something like this:

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

const char * num_to_text[3]={"","1","2"};

int main()
{
    srand(time(0));

    std::cout << "hold esc to quit..." << std::endl;

    int i;

    while(true)
    {
        i = rand() % 2 + 1;

        MessageBox (0, num_to_text[i], "Result", MB_OK);

        if (GetAsyncKeyState(VK_ESCAPE)>>15) break;
    }

    return 0;
}

Last edited on
Topic archived. No new replies allowed.