C-String Array Input Validation

Hi,

The following code I wrote class is supposed to ask the user to input a social security number. The SSN number is stored as a c-string, passed into a function, then the function determines if the SSN is in the correct format.

I was able to write this code previously with multiple loops inside the function for each part of the number, and it worked fine, but the teacher said it would be cleaner to just do all of the validation with one loop as I have below.

The code looks fine to me, but when I run it, if the user enters the correct amount of characters (11), it's like the program never even runs the function. After pressing enter the program just sits there. I checked this because I previous put a cout statement at the beginning of the function to see if it even displays when the correct number of characters is entered, it doesn't.

When the user inputs an incorrect amount of characters (anything but 11) the function is called perfectly, returns a false, and the program finishes as expected.

Can anyone provide any help?

Thank you!

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
43
44
#include <iostream>
#include <cstring>
using namespace std;
bool isValidSSN(char[]);

int main ()
{
    char ssn[80];
    bool result;
    cout << "SSN: ";
    cin >> ssn;
    result = isValidSSN(ssn);
    if (result)
        cout << ssn << " is valid\n";
    else
        cout << ssn << " is not valid\n";
    return 0;
}

bool isValidSSN(char ssn[])
{
    bool hasDigit = true;
    bool hasHyphen = true;
    
    if (strlen(ssn) == 11) // only one loop below if i = 3 check for hyphen, if i = 6 check for hyphen
    {
        for (int i = 0; i < 11; i++)
        {
                while (i < 3 || (i > 3 && i < 6) || i > 6)
                {
                    if (! (isdigit(ssn[i]))) hasDigit = false;
                    
                }
                while (i == 3 || i == 6)
                {
                    if (!(ssn[i] == '-')) hasHyphen = false;
                }
        }
            
            if (hasDigit == true && hasHyphen == true) return true;
        
    }
    return false;
}
Why are line 29 and 34 loops? Where does the value of i inside the loops change? How can the loops terminate if i does not change?
Thank you. I have no idea why I put those as loops, that was a dumb mistake. I fixed them and made them into if statements, like they should have been, and my problem was solved.

Thanks again!!!
Topic archived. No new replies allowed.