This is my first post here, and I am about 3 weeks into learning C++. I wrote this program and it works great but I want to limit it to only except integers. Ideally, I'd like to know if there is a way to do this withing an if statement. If say, the letter b is entered, I'd like it to say something like "invalid entry." can someone help?
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
double leng1,
leng2,
width1,
width2,
rec1,
rec2;
cout << "let's compare the area of two rectangles.\n"
<< "First enter length and the width of Rectangle One in feet\n"
<< "Length: ";
cin >> leng1;
cout << "Width: ";
cin >> width1;
cout << "\nGreat, now the same for Rectangle Two.\n"
<< "Length: ";
cin >> leng2;
cout << "Width: ";
cin >> width2;
rec1 = (leng1 * width1);
rec2 = (leng2 * width2);
cout << fixed << showpoint << setprecision(3);
if (rec1 > rec2)
{
cout << "\nRectangle One has an area of " << rec1 << " feet, \n"
<< "which is larger then Rectangle Two's area of " << rec2 << " feet.";
}
elseif (rec1 < rec2)
{
cout << "\nRectangle Two has an area of " << rec2 << " feet, \n"
<< "which is larger then Rectangle One's area of " << rec1 << " feet.";
}
elseif (rec1 == rec2)
cout << "\nRectangles One and Two are equal";
else
cout << "Invalid entry";
return 0;
}
In the event that there is no more remaining input the function exits the while loop and returns 0. You can easily expand the function by e.g. making it a template and/or adding parameters that limit the range of accepted values.