0

When I run this and after I select my number as a player, Computer returns me two outputs (instead of one...). I have no idea why, could you please help me explain why that happens?

#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>

using namespace std;

int random(int a, int b)
{
    int num = a + rand() % (b + 1 - a);
    return num;
}

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

    int myNum;
    cout << "Choose your number, human: ";
    cin >> myNum;

    int min = 1;
    int max = 100;
    int comp;

    string player;

    while(1) {
        comp = random(min, max);
        cout << "Computer: " << comp << endl; // why does this get called twice??
        getline(cin, player);

        if (player == "too high") {
            max = comp - 1;
            cout << "min: " << min << " max: " << max << endl;
        } else if (player == "too low") {
            min = comp + 1;
            cout << "min: " << min << " max: " << max << endl;
        } else if (player == "correct") {
            cout << "Computer found the number..." << endl;
            break;
        }
    }
}
  • 3
    Please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask), and *edit your question* to show us the input that causes the output, and also *show* us the output (actual and expected). I also recommend you [learn how to debug your programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Some programmer dude Feb 03 '18 at 11:55

1 Answers1

1

It's because you are mixing input using >> and getline. getline reads to the next newline, >> does not. After you have entered your number, there is still a newline left behind, you have typed it, but hasn't yet been read. The first time you call getline that left behind newline gets read, and the program doesn't pause. Only on the second time that you call getline does your program pause and wait for you to type something.

Simple way to fix the problem is

int myNum;
cout << "Choose your number, human: ";
cin >> myNum;
// flush pending newline
string dummy;
getline(cin, dummy);
john
  • 85,011
  • 4
  • 57
  • 81
  • 1
    Why not `cin.ignore()`? – Norrius Feb 03 '18 at 12:02
  • @Norrius used like that `ignore` only skips one character, and there could be more pending characters (say a space was entered after the number). The more correct method would be `cin.ignore(numeric_limits::max(), '\n');` but that requires a lot more explanation. – john Feb 03 '18 at 12:05
  • @john yes, I meant the empty parentheses to indicate a function call... I had something like `cin.ignore(256, '\n')` in my mind. – Norrius Feb 03 '18 at 12:07
  • @Norrius No doubt, ignore is the best solution since it doesn't require constructing an unused object. – john Feb 03 '18 at 13:59