Only allowing numeric input error

I'm trying to create a program that allows the user to input 9 numbers, and the program prints that same number but with dashes in between in the format of a social security number (xxx-xx-xxxx). I also have a function that only allows the user to enter 9 characters. The problem i'm having is I need the program to detect when the user is not entering numbers, and then telling them the input is invalid and re looping the program. I can't seem to find anything that works and what i currently have completely stops the program from functioning.

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
37
38
 // Chapter 13. Ex. 24.cpp

#include <iostream>
#include <string>
using namespace std;


int main()
{
	string ssn = "";
	int num;

	cout << "Nine-character Social Security number:	";
	getline(cin, ssn);
	
	if (!(cin >> num))
	{
		cout << "Please enter numbers only" << endl;
		cin.clear();
		cin.ignore(numeric_limits<streamsize>::max(), '\n');
	}
	else cout << "Invalid Input";

	if (ssn.length() == 9)
	{

		//intert hyphens
		ssn.insert(3, "-"); //xxx-xxxxxx
		ssn.insert(6, "-"); //xxx-xx-xxxx
		cout << "Social Security number: " << ssn << endl;
	}
	else
		cout << "Invalid input, make sure it contains 9 numbers only." << endl;
	
	//end if
	system("PAUSE");
    return 0;
}
Last edited on
@ScottSmith1020

First, you have to keep checking and verifying that the input is what is required. Then afterwards, add the hyphens.

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
37
38
39
40
41
42
#include <iostream>
#include <string>

using std::string;
using std::endl;
using std::cout;
using std::getline;
using std::cin;

int main()
{
	string ssn = "";
	bool All_Nums;
	
	do
	{
		All_Nums = true;
		cout << "Nine-digit Social Security number:	";
		getline(cin, ssn);
		if(ssn.length() == 9) // Only allow if input is 9 long
		{
			for(int x=0;x<9;x++)
			{
				if(ssn[x]<'0' || ssn[x]>'9')
					All_Nums = false; // If not 0 to 9, make false
			}
			if(!All_Nums)
				cout << "Your input does not contain only numbers 0 to 9. Please re-input correct social security number"<<endl;
		}
		else
			cout << "That was not 9 numbers. Try again.." << endl;// If NOT 9 long
	}while(ssn.length() != 9 || All_Nums == false);

	//insert hyphens
	ssn.insert(3, "-"); //xxx-xxxxxx
	ssn.insert(6, "-"); //xxx-xx-xxxx

	cout << "Social Security number: " << ssn << endl;

	system("PAUSE");
	return 0;
}
Last edited on
Thanks so much! I've been struggling with our string lesson at school and this helps me immensely, and the program works perfectly, thanks!
@ Databend (ScottSmith1020)

Glad to be of help.
Topic archived. No new replies allowed.