Can anybody could help me in modifying this program?
It asks for the user to enter his/her age. When the input returns it displays a message.
However I want the program to reconize if the user types in a letter or word. The coniditonal statement I have set up only seems to work when the age variable is set to CHAR. But if its an INT, data type; the window closes whenever it goes to check for a letter.
Im using Codeblocks with Vista 32bit.
Here's the code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
char age;
cout<<"Please input your age: ";
cin>> age;
cin.ignore();
if ( age < 100 ) {
cout<<"You are fairly young.\n";
cin.ignore();
return 0;
}
else (!age); {
cout<<"That's a letter! ";
cin.ignore();
return 0;
}
}
The shell window in Windows closes immediately after the program exits. Because of this,
you need to pause your program in some way. Search around here; there are plenty of
posts that show ways to do that.
The variable age, only checks if the user enters a letter or number. The problem I'm having is with double digits. Let's say someone entered 34. Because Age is a CHAR, it can only retain 1 byte of info. So is there a way to retain both numerical and character data without having to assign another variable?
So far it grants having typed a letter or 1's value and prints.
Use std::getline to read into a std::string as firedraco mentioned, then
convert the string to integer. In this case, if the conversion fails, you
know the input was not numeric.
Look up strtoul(); it is what you will need.
(Or boost::lexical_cast<> if you have and can use boost).
Alright, I hope one of you guys are still reading this because I just tested out my program again to debug and IT WORKS.
I didn't try the strtoul or std::getline that was mentioned above. But here's the remaining code. The only thing I change was the age, statement for else. Could someone explain how terminating the else statement before it writes out was fixed?
#include <iostream>
#include <string>
using namespace std;
int main()
{
char age;
cout<<"Please input your age: ";
cin>> age;
if ( age < 100 ) {
cout<<"You are fairly young.\n";
return 0;
}
else (!age); {
cout<<"That's a letter! ";
cin.ignore();
return 0;
}
}