I'm doing this simple program that checks for number validation and I have an infinite loop in it. I can't figure out how to stop it. It's supposed to check for numeric digits only, but when it finds something other than the above, it hangs up in the loop. Could someone please help me? Thanks in advance for your time and help!

*Delilah*

cout << "Enter a social security number without dashes: ";
    getline(cin, socialNum);
    numChars = static_cast<int>(socialNum.length());
    
    while (subscript < numChars)
    {
          currentChar = socialNum.substr(subscript, 1);
          if (currentChar == "0"
          || currentChar == "1"
          || currentChar == "2"
          || currentChar == "3"
          || currentChar == "4"
          || currentChar == "5"
          || currentChar == "6"
          || currentChar == "7"
          || currentChar == "8"
          || currentChar == "9")
          {
          subscript = subscript + 1;
          }
          else
          cout << "Please enter digits only." << endl;
          //end if
    }//end while

Recommended Answers

All 6 Replies

Because, in checking the current char, if there's a non-numeric character, the subscript's position is not changing, so it keeps checking the same character oiver and over again. Maybe you could try a validated loop exit?

bool valid = true;
while ((subscript < numChars) && (valid))
    {...
        if(...)
        {...}
        else
        {
            cout<<"Please enter digits only"<<endl;
            valid = false;
        }
    }

I tried your suggestion. It didn't recognize it as false and displayed the output as normal.

What exactly do you want to do if there is a non number in the string? that will determine what you need to do.

It needs to send an error message and it should give them another chance to input the info, but if it doesn't it's not a big deal. It can just stop and exit with the error message for this one.

I would suggest using an implementation like Nichito purposed.

bool valid = true;
do
{
    cout << "Enter a social security number without dashes: ";
    getline(cin, socialNum);
    size_t size = socialNum.size(), counter = 0;
    while(counter < size)
    {
        if(...)
        {...}
        else
        {
            valid = false;
            cout << "Invalid input!\n";
            break;
        }
    }
} while (!valid);

It works. Thank you all for your help and suggestions! I greatly appreciate it!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.