Hello Im a few days into learning C++ and was doing an assignment for a class. but when I type (a letter) Ex. "C" instead of an invalid integer like the 1st statement it just produces
-858993460 is even.
-858993460 is Divisible by 4.
-858993460 is Divisible by 5.
-858993460 is not all Divisible by 3,4 or 5..
/*
Write a program that asks the user to enter any integer.
The program outputs whether the number is negative or positive (consider the number 0 as positive),
whether it is odd or even,
and whether it is divisible by any of 3, 4, and 5.
For example, if the input number is -90, the output should say something like:
The number is negative, even, and divisible by 3, 5.
*/
#include <iostream>
usingnamespace std;
int main()
{
int x;
cout << "Please enter an integer; " << endl;
if (!(cin >> x))
{
cout << "Invalid integer" << endl;
}
elseif (x >= 0)
{
cout << x << " is positive." << endl;
}
elseif (x<0)
{
cout << x << " is negative." << endl;
}
if (x % 2 == 0)
cout << x << " is even." << endl;
else
cout << x << " is odd." << endl;
if ((x % 3 == 0))
{
cout << x << " is Divisible by 3." << endl;
}
if ((x % 4 == 0))
{
cout << x << " is Divisible by 4." << endl;
}
if ((x % 5 == 0))
{
cout << x << " is Divisible by 5." << endl;
}
if ((x % 3 == 0) && (x % 4 == 0) && (x % 5 == 0))
{
cout << x << " is Divisible by all 3,4 and 5." << endl;
}
else
{
cout << x << " is not all Divisible by 3,4 or 5." << endl;
}
system("pause");
return 0;
}
its not really part of the homework since I did everything it was asking for already. but I have a feeling that this I would have to do this in the future so any suggestions?
When you enter an invalid character x is not modified. In your case it remains uninitialized. All calculation should be in one else branch not else if.