input twice

Aug 23, 2014 at 7:27am
Hi, I am trying to figure out why whenever I input a number, I have to input it twice to go through the GetParam function.
Example 1: (If I input a number less than the minimum.)

Please enter the monthly payment: 0
0
Please enter the monthly payment:

Example 2: (If I input a number that is between the minimum and maximum)

Please enter the monthly payment: 5
5
5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  #include <iostream>
#include <string>

using namespace std; 

double GetParam(string prompt, double min, double max)
{
	double number;
	cout << prompt;
	cin >> number;

	while ((!(cin >> number)) || (number > max || number < min))
	{
		cin.clear(); 
		cin.ignore();
		cout << prompt; 
		cin >> number;
	}

	return number; 
}

int main()
{
	double monthpay;
	
	monthpay = GetParam("Please enter the monthly payment: ",1,100000);
	cout << monthpay << endl;
	return 0; 
}
Aug 23, 2014 at 7:31am
remove line 10 and 17 then look closely at line 12.
Aug 23, 2014 at 7:37am
I tried it and it works but I don't understand how come you remove cin >> number from line 10 and 17. In my sense, cin >> number is asking the user to input again and again until it does not satisfy the while loop and return the number.
Aug 23, 2014 at 7:55am
Line 12 asks for the number and stores it in the double variable "number", what is the need to ask for it before the while loop or in it?
Topic archived. No new replies allowed.