Well... I don't know how you can prevent the user from typing characters, but I can help you with a function that changes a string to a int (atoi).
If the user types an invalid number, the program will show a message.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {
char age[10];
int intr = atoi ( age );
cout << "How old are you?" << endl;
cin >> age;
//If the user typed an invalid number or a negative number shows a message
if ( age[0] == 0 ){
cout << "\a" << "You typed an invalid number" << endl << endl;}
if ( age[0] <= '0' ) {
cout << "\a" << "You typed an invalid number" << endl << endl;}
else
{
cout << "You have " << intr << " years old\n\n";
}
//Prevents the program to close after the user types his/her age
system("PAUSE");
return 0;
}
This is the best code I know. Try that, I hope it works for you, it didn't worked for me on the compiler I use... But I have tried that before in other programs. If someone knows what's the problem, fix it please.