Why is the last "else" not working, if for example i type letters the program will just close. Thank you
using namespace std;
int main ()
{
int year = 2013;
int input;
cout << "What year are you in ?\n";
cin >> input;
if (input == year)
cout << "Congrats, you know what year it is.\n";
else
{
if (input < year)
{
cout << "You are living in the past.\n";
}
else
{
if (input > year)
{
cout << "Back to the future with you.\n";
}
else
cout << "What are you smoking man?\n";
}}
char x;
cin >> x;
return 0;
}
1
Expert's answer
2013-02-01T09:27:21-0500
Your last "else" are not working because if youtype letters your input does not match the type of the variable in which you try to store it. To fix this problem you need to use function"atoi". See the program below.
#include <iostream> #include <stdlib.h>
using namespace std;
int main () { int year = 2013; int input; char input_str[10];
cout << "What year are you in ? "; cin >> input_str;
input = atoi(input_str);
if (input == 0) { cout << "What are you smoking man? "; } else { if (input == year) cout << "Congrats, you know what year it is. "; else { if (input < year) { cout << "You are living in the past. "; }
else { cout << "Back to the future with you. "; } } }
Comments
Leave a comment