Need help! Looping problem!

How can I loop this to make it work where when the user enters a negative value for cin statements, it checks and tells the user they have an invalid input and to try again, and loops around. I already have a do while loop and I need to make it to where the program will check for invalid inputs like negative values and it will loop again and ask the questions until they enter the right value.

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
  #include <iostream>

using namespace std;

double calc_Inflation(double yearAgo_price, double currentYear_price);


int main()
{
	double yearAgo_price = 0.00;
	double currentYear_price = 0.00;
	double inflation = 0.00;
	char again;

	do
	{
        cout << endl;
		cout << " What was the price of the item a year ago? " << "$";
		cin >> yearAgo_price;
		cout << endl;
		cout << " What is the price of the item this year? " << "$";
		cin >> currentYear_price;
		cout << endl;
       

       if((yearAgo_price < 0) || (currentYear_price < 0))
        { 
            cout << "You have entered an invalid input!" << endl; 
            cout << "Please try again." << endl;
        }
        else
        {
        
        }        
	}
		inflation = calc_Inflation(yearAgo_price, currentYear_price);
		cout << " The inflation rate is " << inflation * 100 << "%." << endl;
		cout << endl;
		cout << endl;
		cout << " Do you wish to continue? [Y for Yes/N for No] ";
		cin >> again;
		cout << endl;

	while ((again == 'Y') || (again == 'y'));

	system("pause");
	return 0;
}

//----------------------------------------------------------------------------
double calc_Inflation(double yearAgo_price, double currentYear_price)
{
	return ((currentYear_price - yearAgo_price) / yearAgo_price);
}
1
2
3
4
5
6
7
8
9
while(input < 0)
{
	std::cin >> input;
	if(std::cin.fail())
	{
		std::cin.clear(); //this is to clear the stream error state in case someone enters in a letter instead of a numerical value
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //this exacts all the characters from the stream so we start out with a fresh stream to get the input
	}
}
Last edited on
where is that supposed to go in the program.
I cant use all that stuff I haven't learned anyways.
Put all the code that it supposed to repeat based on the input inside that while loop.
I haven't learned those functions so I cant use that code.
Have you learned std::cin?
Topic archived. No new replies allowed.