Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I NEED A C++ CODE! Many websites ask for phone numbers. The problem is that ther

ID: 3716088 • Letter: I

Question

I NEED A C++ CODE!

Many websites ask for phone numbers. The problem is that there are many different ways to represent a phone number. Examples include 817-555-1234, 817 555 1234 (c), and (817) 555-1234 x23. Write a C++ program which inputs a string containing a phone number in any format and outputs it in the standard format. Your program may use either C-Strings or the C++ string Class, but should not mix them. For this assignment, the standard format is (817) 555-1234.

Sample Output (inputs in bold)

1. Please enter a phone number: 817-555-1234 The properly formatted number is (817) 555-1234

2. Please enter a phone number: (817)515 7259 x23 The properly formatted number is (817) 515-7259

3. Please enter a phone number: 214-555-999 The phone number must have at least 10 digits

4. Please enter a phone number: 800**4444xxx333 The properly formatted number is (800) 444-4333

Thank you.

Explanation / Answer

Solution:

Please find comments

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

int main() {

string input;
string output;
int countOfDigits = 0;

cout << "Please enter a phone number:";
getline(cin, input) ;

std::string::iterator iter;
for(iter = input.begin(); iter != input.end(); iter++) {
if(isdigit(*iter)) {
output.push_back(*iter);
countOfDigits++;
}
}

if(countOfDigits < 10){
cout << "The phone number must have at least 10 digits."<<endl ;
exit(0);
}

//keeping only the first 10 digits in mobile no input string
output = output.substr(0,10);

//The simplest approach to format the
//entered mobile no is; since we know the format is
// fixed for a 10-digit no so we can place the special
//characters i.e. '-' or '(' by hardcoding the
//index positions
output.insert(0,"(");
output.insert(4,")");
output.insert(8,"-");

cout<< "The properly formatted nunber is :" ;
cout<< output << endl;

return 0;
}