Zebra0.com

cpp stringsValidating String as Social Security number

Validating String as Social Security number

Validating String as Social Security number

// Programmer: Janet Joy
// Check if a string is a valid Social Security number
// IE: length must be 9 and each character is a digit
#include "pch.h"
#include <iostream>
#include<string>
using namespace std;
int main()
{
	string digits = "0123456789";
	string str;
	bool ok = true; //assume true until found false
	cout << "Enter a social security number:"; 
	getline(cin, str); //reads the whole line
	if (str.length() != 9) ok = false;
	// check each character to make sure it is a digit
	for (int i = 0; i < str.length(); i++) {
		string ch = str.substr(i, 1); // get one character
		// look for character in digits
		int pos = digits.find(ch);
		// find returns a negative value if not found
		if (pos < 0) ok = false;
	}
	if (ok) cout << "Good\n";
	else cout << "That is not a valid Social Security number\n";
}

To Do:

  1. Run the program and verify that it works.
  2. Modify to use the conditional operator ? to display message.
  3. Modify to accept either 9 digits or with 2 dashes: 123-12-1234

End of lesson, Next lesson: