lundi 24 mai 2021

how to insert only digits in a string

I have this code that should check if the user inputs 3 digits into a string variable:

std::string digits;
bool error = false;

do {
    error = false;

    std::cout << "Type 3 digits. (0 to 9)\n";
    std::cin >> digits;

    if (digits.size() != 3) {
        std::cout << "\nError, you must type 3 digits.\n\n";

        error = true;
    }
    else {
        for (int i = 0; i < 3; i++) {
            if (digits[i] < 0 || digits[i] > 9) {
                std::cout << "\nError, you must type only digits. (0 to 9)\n\n";

                error = true;

                break;
            }
        }
    }
} while (error == true);

This isn't giving any error but still it doesn't work, it correctly checks when user inserts more than 3 characters but even if the input is correct (123) it restarts the loop.

Aucun commentaire:

Enregistrer un commentaire