21312

Sep 20, 2021 at 8:24pm
set up a boolean, eg
bool isvalid{true}; //until proven otherwise, the value is valid..
then loop until happy:
do
isvalid = true; //reset it each loop!
read a number
test it.
for each test, you want something like
isvalid = isvalid && testresult;
while(!isvalid); //loop until you get a valid number

if you want to get fancy you can skip tests once isvalid is false.
Last edited on Sep 20, 2021 at 8:24pm
Sep 20, 2021 at 9:14pm
jonnin gave you the outline of what you need to do.
Something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <fstream>
#include <string>
//  #include<bits/stdc++.h> 

using namespace std;

bool isValid(const string& phone)
{
    const string areaCode[] = { "520", "620","405", "550", "650" };

    if (phone.length() != 10)
    {
        cout << "Invalid phone number  ," << endl;
        return false;
    }
    // only focus first tree numbers to identify it is in right area code
    string area_C = phone.substr(0, 3);
    // Use the find function to check if the code is valid
    if (find(begin(areaCode), end(areaCode), area_C) == end(areaCode))
    {
        cout << "( !!ERROR!! ,Wrong area code or Invalid phone Number ! ) \n ";
        return false;
    }
    //  Passed all tests
    cout << "The phone number is valid" << endl;
    return true;
}

int main()
{
    string phoneNumber;

    //Print the Company name
    cout << "********************************************************************\n";
    cout << "          X Y Z  Regular (wired) Telephone Service \n";
    cout << "*********************************************************************\n";

    cout << "Enter the your phone number: ";
    while (1)   //  Loop forever if not valid
    {
        // Let user enter their phone number         
        cin >> phoneNumber;
        if (isValid(phoneNumber))
            break;  //  break out of loop
        //  We've already displayed what is wrong
        cout << "Please re-enter your phone number" << endl;
    }
    //  Got a valid phone number, exit the program
    return 0;

}

Sep 20, 2021 at 10:55pm
I guess another one got their answer and spannered the thread.
Sep 20, 2021 at 11:45pm
The question was essentially, "How do I handle user input during an interactive session?"
Topic archived. No new replies allowed.