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
Re: C++ infinite loop 80 80

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;
        }
    }
Re: C++ infinite loop 80 80

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

Re: C++ infinite loop 80 80

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

Re: C++ infinite loop 80 80

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.

Re: C++ infinite loop 80 80

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);
Re: C++ infinite loop 80 80

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 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.