Age program advise

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;
}
}
1
2
3
4
if( !cin ) 
    cout << "That's a letter!";
else if( age < 100 ) 
    // etc 
Jsmith

The DOS window still insists on closing. Could it have something to do with the user, pressing the enter button for the command to start?
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.
You can use an std::string.
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).
Im sorry but Im still new at this.

Where do you write the std::getline and std::string?

Do you declare it or is it function?

Could you write it out that's involved with my code?
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;
}
}
You need to check !cin, not !age, and that ';' isn't supposed to be there (otherwise that section of code will always run).
Topic archived. No new replies allowed.