while loop repeats 1 more time??

I would like to take this oppertunity to say hi to everyone.

But I have a small problem I cant seem to work out. Its a simple dice program I created to try out the rand() feature but when I tell the program to roll again it does it twice.

Here's the code

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
// Simple Dice program while learning c++
// example of rand() numbers between 1 and 6

#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <time.h>

using namespace std;

//enum dice {One =1, Two, Three, Four, Five, Six} die1, die2;

int roll_die()
{
    int dice_rolled, die_rolled1, die_rolled2;

    die_rolled1 = rand() % 6 + 1;
    cout << die_rolled1 << " + ";
    die_rolled2 = rand() % 6 + 1;
    cout << die_rolled2 << " = ";

    dice_rolled = die_rolled1 + die_rolled2;

    cout << dice_rolled << endl;

    return 0;
}

int main()
{
    char no;
    srand (time(NULL));

    do
    {
        roll_die();
        cout << "Roll again? (y/n)";
        no = getchar();
        cout << endl;
    }
    while(no != 'n');


    return 0;
}


Any help would be greatly appreciated, especially since I've been up all night learning c++ and now can hardly stay awake. heh
1
2
3
4
5
6
7
8
do
    {
        roll_die();
        cout << "Roll again? (y/n)";
        no = getchar();
        cout << endl;
    }
    while(no != 'n');

Just to make sure, this part says 'n' and not 'n'?

BTW: You are using C functions. You gotta get the following into your head: Anything that comes from C is evil (which is just a fancy way of saying, don't use it unless there is no reasonable alternative).
I was going for

do .. while not equal to 'n'.

I wanted the program to roll again unless i entered 'n'. However it seems to roll twice before I get asked again.

for example;

1 + 4 = 5
Roll again? (y/n)y

5 + 6 = 11
Roll again? (y/n) <-- I dont get to enter anything here
2 + 2 = 4 <-- Maybe this is the extra roll of the dice
Roll again? (y/n)n

I take it, its the getchar thats C I'll rectify that later :D
1
2
3
4
5
6
7
8
    do
    {
        roll_die();
        cout << "Roll again? (y/n)";
        cin>>no;
        cout << endl;
    }
    while(no=='y');


I think this works.But it exits loop for any character other than 'y',not just 'n'.
Last edited on
Thanks that worked a treat, I should have used the cin to begin with anyway dont know what I was thinking
If you wonder why, the next character getchar eats is a '\n' for the enter the user entered. That's why you should avoid C functions if possible, you will only confuse yourself.
Topic archived. No new replies allowed.