1

This is supposed to check if an entered string is a valid license number. A valid number cannot have any lower case letters or spaces. If I enter "cat", it should see that the character "c" is lower so it should set bool isValid to false, break from the loop and then print "cat is not a valid license number." However it doesn't and it just makes the bool isValid to whatever I set it to in the beginning which was true. So if I initialized it to false and input "CAT" isValid would still be false.

int main()
{
    // Input
    cout << "Enter a valid license number: ";
    string license_number;
    getline(cin, license_number);
    cout << endl;

    // Initialize boolean
    bool isValid = true;

    // Loop to check for space or lowercase
    for (int i = 0; i < license_number.size(); i++)
    {
        if (isspace(license_number[i]) || islower(license_number[i]))
        {
            bool isValid = false;
            break;
        }

        else
            bool isValid = true;
    }

    // Output
    if (isValid == true)
        cout << license_number << " is a valid license number." << endl;

    else
        cout << license_number << " is not a valid license number." << endl;

    return 0;
}
Konachan
  • 11
  • 4

2 Answers2

0

The problem is here:

bool isValid = false;
    break;

You're not changing your isValid variable. Instead, you're making a new isValid that shadows the original isValid, and that new variable is discarded immediately as it goes out of scope right afterwards. As a result, your original isValid is unaffected. Remove the bool in this line and it'll work.


Other than that you can also remove this part

else
    bool isValid = true;

Because isValid is true anyway when this part of the code is reached. Also instead of if (isValid == true) you can simply write if (isValid). You could even simplify the code like this:

// Loop to check for space or lowercase
for (int i = 0; i < license_number.size(); i++)
{
    if (isspace(license_number[i]) || islower(license_number[i]) )
    {
        cout << license_number << " is not a valid license number." << endl;
        return 0;
    }
}

cout << license_number << " is a valid license number." << endl;

return 0;

Also, if you have the time, have a look at Why is "using namespace std;" considered bad practice?.

Blaze
  • 16,736
  • 2
  • 25
  • 44
0

You just need to remove the bool type from the for loop (in if and else condition) - it defines a new local variable isValid which shadows the isValid definition which is outside the loop (under comment // Initialize boolean) & this local definition cease to exist as soon as the command flow go out of the block where it has been defined.

And outside that block the definition isValid = true again comes into play (which remained untouched from the processing logic).

Agrudge Amicus
  • 1,033
  • 7
  • 19