Invalid Input Check....

Heres the Problem: Write a program to gauge the rate of inflation for the past year. The program asksfor the price of an item (such as a hot dog or a one-carat diamond) both one year ago and today. It estimates the inflation rate as the difference in price divided by the year-ago price. Your program should allow the user to repeat this calculation as often as the user wishes. Define a function to compute the rate of inflation. The inflation rate should be a value of type double giving the rate as a percentage, forexample 5.3 for 5.3%.

How can I check that the user makes sure to enter a double so when the user does enter a character, it says you've entered a invalid input. I have this so far but it doesn't work.

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
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>

using namespace std;

double getInput(double prices);
double calc_Inflation(double oldPrice, double newPrice);


int main()
{
	double yearAgo_price = 0.00;
	double currentYear_price = 0.00;
	double inflation = 0.00;
	double prices;
	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;

		inflation = calc_Inflation(yearAgo_price, currentYear_price);
		cout << " Inflation Rate is : " << inflation * 100 << "%." << 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 getDoubleInput()
{
    
    double prices;
    
    while ( !cin )
    {
	cout << "You have entered an invalid input! " << endl; 
	cout << "Please try again and enter a double." << endl;
	cin >> prices;
        cin.clear();
        cin.ignore();
    }
    
    return prices;
    
} 

double calc_Inflation(double oldPrice, double newPrice)
{
	return ((newPrice - oldPrice) / oldPrice);
}
Line 49. The loop executes only if cin is bad. That implies that unrelated input operations before this function were foul.

Line 53. You have just established that cin is bad and the first thing you attempt is to read?

Order of things you do ...
Can you show me how this could be fixed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
	double test;
	cout<<"Enter a character instead of a double: ";
	if(!(cin>>test))
		cout<<"Wrong input"<<endl;
	else
		cout<<"Good input"<<endl;
	system("pause");
	return 0;
}
Topic archived. No new replies allowed.