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

Dani AI

Generated

As correctly pointed out, the loop became infinite because the code never advanced past a bad character, so it kept re-checking the same position. The original use of substr(...) to compare one-character strings and listing every digit separately is both inefficient and easy to get wrong. Below are small, safer alternatives and a few hardening tips that build on ’s re-prompt idea and the fact that ’s fix later worked.

A compact, zero-loop check: use find_first_not_of to detect any non-digit in one call.

std::string socialNum;
std::getline(std::cin, socialNum);

if (!socialNum.empty() && socialNum.find_first_not_of("0123456789") == std::string::npos) {
    // all characters are digits
} else {
    std::cout << "Invalid input — digits only.\n";
}

A slightly more locale-safe approach uses <cctype> and std::all_of. Important: cast each char to unsigned char before calling std::isdigit to avoid undefined behavior on negative char values.

bool onlyDigits = !socialNum.empty()
  && std::all_of(socialNum.begin(), socialNum.end(),
                 [](unsigned char c){ return std::isdigit(c); });

Practical tips: prefer operator[] or these one-shot checks instead of substr; use std::string::size_type (or size_t) for indexes when you must loop; decide whether to allow spaces or dashes (strip them first if you do); and always re-prompt in a simple outer loop that validates the whole string, rather than trying to recover inside the character-scan loop. These changes keep the logic clear and eliminate the kind of infinite-loop trap you encountered.

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.