kauajuno
kauajuno

Reputation: 45

One more question about using a while to "embrace" my code instead of calling main()

So, in this link -> Problems doing a while loop I did a question about a problem dealing with the use of while instead of calling main(), and it helped me, my code worked, but there's a new little problem. I'mma show it with a kind of "Dice Roller Code"

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int main(){

    srand((unsigned)time(NULL));
    int totalSides, dice, modifier;
    char c, d;

    printf("Welcome to the dice roller!\n");
    printf("If you wanna roll the dice, press 'r'. If you wanna quit, press 'q': ");
    scanf(" %c", &c);

    while(c == 'r'){

        printf("How many sides does the dice you want to roll have? Answer with a int number: ");
        scanf("%d", &totalSides);
        printf("Do you need any modifier? Press 'a' to add, press any other key to dispense: ");
        scanf(" %c", &d);
        if(d == 'a'){
            printf("Insert your modifier value: ");
            scanf("%d", &modifier);
            printf("\n");
        }
        dice = rand() % totalSides + 1;
        printf("You've got a %d!\n", dice);
        if(d == 'a'){
            printf("But you've got a %d modifier...\n", modifier);
            dice = dice + modifier;
            printf("Then, you got a %d!", dice);
        }

        printf("\n\n\n\n");
        repeat();
        c = repeat();
        printf("\n\n\n\n");
    }
}

int repeat(){
    char c;
    printf("Do you want to reroll? Press 'r' to reroll, pres 'q' to quit: ");
    scanf("%c", &c);
    return c;
}

The program works very well, but in the output I got the same sentence two times, like: "Do you want to reroll? Press 'r' to reroll, pres 'q' to quit: Do you want to reroll? Press 'r' to reroll, pres 'q' to quit: "

How can I solve this?

Upvotes: 0

Views: 45

Answers (1)

Kyle
Kyle

Reputation: 330

You are calling repeat twice, so therefore it is printing twice.

repeat();
c = repeat();

Try replacing the first call to repeat to getchar(). This will consume the character entered after the modifer line.

getchar();
c = repeat();

It looks like you are just starting to learn C, and it might be worthwhile to read a book on the matter. One that I can recommend is Modern C. It's available free online, or you can buy a print version.

Upvotes: 2

Related Questions