0

I have a win/lose game in c++. My problem is that at the beginning, after I set the y value, my code does two rounds, but I want it to do only one. I don't understand why, so I need help. This is the only problem that I am having. The code is here:

#include <iostream>
#include <ctime>
#include <conio.h>

using namespace std;

int main()
{
    int x, y, wins = 0, fails = 0;
    char key;

    srand(time(NULL)); // seed for random number generation

    cout << "Enter the value of y (1-200): ";
    cin >> y;

    while (true)
    {
        double prob = (double)y / 20.0; // calculate probability
        double rand_num = (double)rand() / RAND_MAX; // generate a random number between 0 and 1
        x = (rand_num < prob) ? 1 : 0; // determine if player has won or lost
        if (x == 1)
        {
            cout << "Congratulations, you won 100000 dollars!!!\n";
            wins++;
        }
        else
        {
            cout << "You lost, try again...\n";
            fails++;
        }
        cout << "Wins: " << wins << ", Fails: " << fails << endl;
        key = getch(); // wait for user input
        if (key == 'q' || key == 'Q')
        {
            continue; // generate a new random number
        }
        else if (key == 'r' || key == 'R')
        {
            wins = fails = 0; // reset variables
           
        }
    }

    return 0;
}

This is what appears on the console after i set the y value ( in this example:6) and press Enter:

Enter the value of y (1-200): 6
You lost, try again...
Wins: 0, Fails: 1
You lost, try again...
Wins: 0, Fails: 2
VSCDesktop
  • 21
  • 1
  • 4
    You are mixing formatted input (`std::cin >> ...`) with unformatted input ( `getch()`). `std::cin >> ...` will leave the newline in the steam so `getch()` will read that in the first iteration of the `while` loop. – Ted Lyngmo Apr 03 '23 at 17:19
  • Using your posted code, I am unable to reproduce this problem on Windows 7 using Microsoft Visual Studio 2017. Please specify exactly which platform you are using. Also, please double-check that your posted code actually reproduces the problem when you press `6` followed by `ENTER`. – Andreas Wenzel Apr 03 '23 at 17:29
  • I would just replace `key = getch();` with `cin >> key;`. That should work, although you'll probably need to press the enter key after pressing q. – john Apr 03 '23 at 17:30
  • 1
    you typed a number and then pressed enter, that's two inputs – user253751 Apr 03 '23 at 17:32
  • 1
    See [this question](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction). I'm hesitant to mark this question as a duplicate since that one is specifically about `getline` rather than `getch`, but the reasoning is the same for both. – Miles Budnek Apr 03 '23 at 19:10

0 Answers0