The following is my code. I am just getting started in C++ so there are few concepts I am still stuck on.
This program works well except for one issue – the data type is integer but it is not catching decimal numbers. In my other programs this worked but for some reason it is not working here and it’s frustrating because I don’t know why. Any advice / help would be appreciated.
// 2 integers - determine which of 2 INTEGERS is the largest or if they are equal
#include <iostream>
using std::cout;
using std::cin;
int main ()
{
int integer1;
int integer2;
int remainder1;
int remainder2;
bool flag1 = false;
bool flag2 = false;
cout << "Enter the first integer: ";
cin >> integer1;
while ( flag1 == false)
{
if (!cin.fail())
{
remainder1 = (integer1 % 1);
if (remainder1 != 0)
{
cout << "\nError reading the number.";
cin.clear();
cin.ignore(50, '\n');
cout << "\nError cleared.";
cout << "\nRe-enter the first integer: ";
cin >> integer1;
}
else
{
flag1 = true; }
}
else
{
cout << "\nError reading the number."; cin.clear();
cin.ignore(50, '\n');
cout << "\nError cleared.";
cout << "\nRe-enter the first integer: "; cin >> integer1;
flag1 = false;
}
}
// check input for the second number to make sure it also does not fail (check if not a string)
cout << "Enter the second integer: ";
cin >> integer2;
while ( flag2 == false)
{
if (!cin.fail())
{
remainder2 = (integer2 % 1);
if (remainder2 != 0)
{
cout << "\nError reading the number.";
cin.clear();
cin.ignore(50, '\n');
cout << "\nError cleared.";
cout << "\nRe-enter the second integer: "; cin >> integer2; }
else
{
flag2 = true; }
}
else
{
cout << "\nError reading the number."; cin.clear();
cin.ignore(50, '\n');
cout << "\nError cleared.";
cout << "\nRe-enter the second integer: ";
cin >> integer2; flag2 = false; }
}
// now calculate which integer is largest or whether they are equal
if (integer1 > integer2)
cout << integer1 << " is larger.\n";
if (integer2 > integer1)
cout << integer2 << " is larger.\n";
if (integer1 == integer2)
cout << " These numbers are equal.\n";
return 0;
}