user2993456
user2993456

Reputation:

std::cin not functioning within do-while loop

I am trying to create a simple program that reads in range limits and then creates a random number between those ranges. Everything is functioning in my program, but when I run the code, the first message prints to the user, then I go to type in my max range, push enter, and the cursor just moves to the next line, still asking for input.

I don't see what is causing this in my code, and I am stumped.

Here is my code so far:

#include<iostream>
#include<limits>

using std::cout;
using std::cin;
using std::endl;

int main(){

    int maxRange; //to store the maximum range of our random numbers

    do {
       cout << "Please enter a maximum range \n";
       //use clear funtion to clear the fail bit
       cin.clear();
       //use ignore function to avoid bad input
       cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    } while(!(cin >> maxRange)); //continue loop if cin fails

    int minRange; //to store the minimum range of random numbers

    do {
       cout << "Please enter a minimum range \n";
       //use clear funtion to clear the fail bit
       cin.clear();
       //use ignore function to avoid bad input
       cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    } while(!(cin >> minRange)); //continue loop if cin fails

    int randomNumber = rand() % maxRange + minRange;

    cout << "The random number that you have generated is: " << randomNumber << endl;

    return 0;
}

EDIT: The issue was the ignore function. Here is my working code for the corrected loop:

if(!(cin)){
    cin.clear();
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
   }

Upvotes: 0

Views: 174

Answers (1)

Dmitri
Dmitri

Reputation: 9375

The cin.ignore() in your first do..while() loop discards your first line of input before trying to read a value in the loop condition. Your program does (kind of) work if you enter the maximum range twice, since it successfully reads the second line. Maybe remove the cin.ignore() line in the first loop.

You also have an error later on in selecting the random number, though...

int randomNumber = rand() % maxRange + minRange;

should be maybe:

int randomNumber = rand() % (1 + maxRange - minRange) + minRange;

to get a range of minRange to maxRange inclusive.

Upvotes: 3

Related Questions