Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How to verify total digits and ensure characters are not entered?

+6 votes
asked Jan 19 by Mr. Bill (180 points)
in C++

string phone_number

If asking for a 10 digit phone number for example, how would you ensure 10 digits are entered?  Also, how would you ensure no characters were input by mistake.  I am also curious how to ensure the user doesn't enter past the prompt by mistake (leaving it empty).

2 Answers

0 votes
answered Jan 20 by PARSA HARSHITH (150 points)
#include <iostream>
#include <string>
#include <cctype>

using namespace std;

bool isValidPhone(const string& s) {
    if (s.empty()) return false;
    if (s.size() != 10) return false;

    for (char ch : s) {
        if (!isdigit(static_cast<unsigned char>(ch)))
            return false;
    }
    return true;
}

int main() {
    string phone_number;

    while (true) {
        cout << "Enter a 10-digit phone number: ";
        getline(cin, phone_number);   // allows empty input too (we can detect it)

        if (isValidPhone(phone_number)) {
            break;
        }

        cout << "Invalid input. Please enter exactly 10 digits (0-9) only.\n";
    }

    cout << "Valid phone number: " << phone_number << endl;
    return 0;
}
0 votes
answered Jan 21 by ruuta (200 points)
#include <iostream>
#include <string>
#include <cctype>

bool isValidPhoneNumber(const std::string& phone)
{
    // Check length
    if (phone.length() != 10)
        return false;

    // Check all characters are digits
    for (char c : phone)
    {
        if (!std::isdigit(c))
            return false;
    }

    return true;
}

int main()
{
    std::string phone_number;

    while (true)
    {
        std::cout << "Enter a 10-digit phone number: ";
        std::getline(std::cin, phone_number);

        // Prevent empty input (user just pressed Enter)
        if (phone_number.empty())
        {
            std::cout << "Input cannot be empty.\n";
            continue;
        }

        if (isValidPhoneNumber(phone_number))
        {
            break;  // valid input
        }

        std::cout << "Invalid phone number. Please enter exactly 10 digits.\n";
    }

    std::cout << "Phone number accepted: " << phone_number << "\n";
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...