49.3k views
5 votes
Write a C++ program that prompts the user to enter a Social Security Number in the format ddd-dd-dddd, where d is a digit and check the validity of the SSN (The input may contain either digit or dash and conforms to the mentioned format).

User Ivantod
by
8.2k points

1 Answer

7 votes

Final answer:

A C++ program is provided that prompts for a Social Security Number and checks its validity against the required format. The program ensures the correct format by checking the length, dash positions, and digit characters.

Step-by-step explanation:

The C++ program below prompts the user to enter a Social Security Number (SSN) and checks its validity according to the specified format (ddd-dd-dddd). If the SSN does not conform to the format, it notifies the user that the input is invalid.

#include
#include
#include

using namespace std;

int main() {
string ssn;
cout << "Enter SSN (ddd-dd-dddd): ";
getline(cin, ssn);

bool isValid = true;

if(ssn.length() != 11)
isValid = false;

for(int i = 0; i < ssn.length() && isValid; i++) {
if((i == 3 || i == 6) && ssn[i] != '-') {
isValid = false;
} else if (i != 3 && i != 6 && !isdigit(ssn[i])) {
isValid = false;
}
}

if(isValid)
cout << "The SSN is valid." << endl;
else
cout << "Invalid SSN format!" << endl;

return 0;
}

When run, the program asks for the SSN input, checks for the correct length, the placement of dashes, and whether all other characters are digits.

User Effeffe
by
8.2k points

Related questions

asked Jul 20, 2020 32.8k views
Hasezoey asked Jul 20, 2020
by Hasezoey
8.2k points
1 answer
2 votes
32.8k views
asked Sep 23, 2024 232k views
Bbaassssiiee asked Sep 23, 2024
by Bbaassssiiee
8.2k points
2 answers
1 vote
232k views