0

I am trying to write a coin toss program that loops. However my while loop doesn't work. The program should continue until the user presses something other than 'y', but for some reason after the second pass it ends the program.

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

char coinToss();
int main() {

    char result;
    char ch = 'y';


    srand(time(0));

    while (ch == 'y' || ch == 'Y') {

        result = coinToss();
        printf("The coin toss is %c", result);
        printf("\nToss the coin again?");
        scanf_s("%c", &ch, 1);


    }

}

char coinToss() {

    char result;
    int coin;
    coin = rand() % 2 + 1;
    if (coin == 1) {

        result = 'T';
    }
    else {

        result = 'H';

    }

    return result;
}
Filburt
  • 17,626
  • 12
  • 64
  • 115
HipHop12
  • 23
  • 2
  • 1
    Short summary of the duplicate: Add a leading space in the format string to skip whitespace (including newlines): `scanf_s(" %c", &ch, 1);` – Adrian Mole Nov 12 '20 at 18:31

2 Answers2

4

Doing scanf("%c", &ch); reads whatever the next unread character is, which includes the newline generated by hitting Enter. Since '\n' doesn't equal 'y' or 'Y', this ends your loop. Adding a leading space to the format string will make it discard whitespace. Do scanf(" %c", &ch); instead.

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

char coinToss();
int main() {

    char result;
    char ch = 'y';


    srand(time(0));

    while (ch == 'y' || ch == 'Y') {

        result = coinToss();
        printf("The coin toss is %c", result);
        printf("\nToss the coin again?");
        scanf(" %c", &ch, 1);


    }

}

char coinToss() {

    char result;
    int coin;
    coin = rand() % 2 + 1;
    if (coin == 1) {

        result = 'T';
    }
    else {

        result = 'H';

    }

    return result;
}

The space in front of %c is for buffor pushing the enter as next entered char

Maqcel
  • 493
  • 5
  • 16