checking entry for a valid integer

I have a program that checks two inputs for integer values and it works fine but the code I have now is rather long. If I needed to check for 20 entries, is there anyway I could make the checking for a valid integer process into a function? Here is my code:
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
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main(){

float originalPrice;
float currentPrice;
float percentDecreaseAmount;
float percentDecreaseTotal;


string checkInteger = "";

	while(true) {
	cout << "Please enter the original price: ";
	
	getline(cin, checkInteger);	
	stringstream checkForIntStream(checkInteger);
			if (checkForIntStream >> originalPrice)
			 break;
			cout << "\n\n\n\nInvalid entry, try again.\n";
		}
	cout << "Original price: $" << originalPrice << ".00" << endl;
	
	
	//Prompt user for secondnumber (original price)

	while(true){
	cout << "Enter the second number: ";
	
	getline(cin,checkInteger);
		
	stringstream checkForIntStream2(checkInteger);
		if(checkForIntStream2 >> currentPrice)
			if(originalPrice > currentPrice )
		 break;
		cout << "\n\n\n\nInvalid entry, try again.\n";
	}
	
	percentDecreaseAmount = originalPrice - currentPrice ;
	percentDecreaseTotal =  percentDecreaseAmount / originalPrice   ;
	
	cout << "\n\n\nThe percent decrease from: $"<< originalPrice << ".00 to $" << currentPrice << ".00 is: " ;
	cout << "%" << percentDecreaseTotal * 100 << endl;
			else
			cout << "The original price must be greater than the current price, please try again.\n";
			
}
1
2
3
4
5
// Returns true if the string "checkInteger" can be parsed as an integer in the range
// [ std::numeric_limits<int>::min() .. std::numeric_limits<int>::max() ].
bool is_integer( const std::string& checkInteger ) {
    // Lines 21-23 here, with slight modification
}

Topic archived. No new replies allowed.