How do you prevent someone from typing in text?

Example

#include <iostream>

using namespace std;

int main()
{

int age;

cout << "How old are you? ";
cin >> age;

}

I don't know how to prevent anyone from typing in text for age
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#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.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;
int main()
{
  char age[10];
  cout << "How old are you?" << endl;
  cin >> age;
  if(age[0] == '0' || age[0] == '-')
  {
    cout << "Invalid age entered" << endl;
    system("pause");
    return 1;
  }
  for(int c = 0; age[c] != '\0'; c++)
  {
    if(((int)age[c] < 48) || ((int)age[c] > 57))
    {
      cout << "Invalid age entered" << endl;
      system("pause");
      return 1;
    }
  }
  cout << "You are " << age << " years old" << endl;
  system("pause");
  return 0;
}

If you need any explanation of this let me know.
Last edited on
Topic archived. No new replies allowed.