If a letter is entered for the starting number, an error message is displayed, but before the error message is displayed the cout statement for the end number is executed.Code:#include < iostream >
using namespace std;
int main()
{
int num;
int num2;
int i;
int j;
cout << "Enter a starting number" << endl;
cin >> num;
cout << "\nEnter an end number" << endl;
cin >> num2;
while ( cin.fail() || num % 2 != num2 % 2 )
{
cin.clear ();
cin.ignore ( INT_MAX, '\n' );
cerr << "\nError (NO MIDDLE NUMBER FOUND)...re-enter..." << endl;
cerr << "\nStarting number: ";
cin >> num;
cerr << "\nEnd number: ";
cin >> num2;
}
if ( num > num2 )
{
for ( i = num2, j = num; j != i; i++, j-- )
{
;
}
}
else if ( num == num2 )
{
cout << "\nBoth numbers are the same" << endl;
exit ( EXIT_SUCCESS );
}
else
{
for ( i = num, j = num2; j != i; i++, j-- )
{
;
}
}
cout << "\nThe number between the numbers you entered is " << i << endl;
return 0;
}
How can I prevent that cout statement from executing before the error message? Why does that cout statement even execute in the first place?
I came up with the solution below, but it's too lenghty, and it uses a goto statement. :(
Code:#include < iostream >
using std::cout;
using std::cin;
using std::cerr;
using std::endl;
int main()
{
int num;
int num2;
int i;
int j;
START://GOTO LABEL
cout << "Enter a starting number" << endl;
cin >> num;
while ( cin.fail() )
{
cin.clear ();
cin.ignore ( INT_MAX, '\n' );
cerr << "\nError...re-enter..." << endl;
cerr << "\nStarting number: ";
cin >> num;
}
cout << "\nEnter an end number" << endl;
cin >> num2;
while ( cin.fail() )
{
cin.clear ();
cin.ignore ( INT_MAX, '\n' );
cerr << "\nError...re-enter..." << endl;
cerr << "\nEnd number: ";
cin >> num2;
}
if ( num % 2 != num2 % 2 )
{
cerr << "\nError (NO MIDDLE NUMBER FOUND)...re-enter..." << endl;
system ( "pause" );
system ( "cls" );
goto START;
}
if ( num > num2 )
{
for ( i = num2, j = num; j != i; i++, j-- )
{
;
}
}
else if ( num == num2 )
{
cout << "\nBoth numbers are the same" << endl;
exit ( EXIT_SUCCESS );
}
else
{
for ( i = num, j = num2; j != i; i++, j-- )
{
;
}
}
cout << "\nThe number between the numbers you entered is " << i << endl;
return 0;
}