I need to create a C++ program that makes the user enter a phone number using st
ID: 3787999 • Letter: I
Question
I need to create a C++ program that makes the user enter a phone number using string and if statements. It needs to check whether the user entered a valid 10 digit phone number and report an error message if the phone number entered is too short or too long. It should show the phone number in the format (XXX) XXX-XXXX
It should look like this:
Please enter a 10 digit phone number (no spaces, no punctuation): 1112223333
You entered: (111)222-3333
It should look like this if the user doesnt put enough numbers:
Please enter a 10 digit phone number (no spaces, no punctuation): 11122233
Sorry! That phone number is invalid.
Please run the program again.
Explanation / Answer
#include<iostream>
#include<string>
using namespace std;
int main()
{
string phone;
cout << "Please enter a 10 digit phone number (no spaces, no punctuation): ";
cin >> phone;
//check if phone number is contains only numbers
for (int i = 0; i < phone.length(); i++)
{
if ((phone[i] >= '0' && phone[i] <= '9'))
continue;
else
{
cout << "Phone numbers contains charactes other than numbers" << endl;
return -1;
}
}
if (phone.length() < 10)
{
cout << "Phone number is too short" << endl;
}
else if (phone.length() > 10)
{
cout << "Phone number is too long" << endl;
}
else
{
cout << "You entered: ";
// show the phone number in the format (XXX) XXX-XXXX
cout << "(";
//after opening bracket , print first 3 chars
for (int i = 0; i < 3; i++)
{
cout << phone[i];
}
cout << ")";
//after closing bracket , print 3 chars
for (int i = 3; i < phone.length() - 4; i++)
{
cout << phone[i];
}
cout << "-";
//print last 4 charecters after '-'
for (int i = phone.length() - 4; i < phone.length() ; i++)
{
cout << phone[i];
}
}
}
-----------------------------------------------------------------------------------------------------
//output
Please enter a 10 digit phone number (no spaces, no punctuation): 1112223333
You entered: (111)222-3333
Please enter a 10 digit phone number (no spaces, no punctuation): 11122233334
Phone number is too long
Please enter a 10 digit phone number (no spaces, no punctuation): 111222333
Phone number is too short
Please enter a 10 digit phone number (no spaces, no punctuation): 111222333h
Phone numbers contains charactes other than numbers
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.