Hello I recently came across this problem for my programming class that requires me to build a program that takes in phone numbers in varying formats and out puts it as (xxx) xxx-xxxx . I've built something that works however my professor pointed out that my program should only include digits before formatting in case a user where to use other characters such as ' . ' . My questions is how do I get this to work with what I have now or do I need to start over from scratch?
#include <iostream>
#include <string>
usingnamespace std;
// main routine
int main()
{
// local variables
bool ValidNumber = false;
string phoneNumber;
while (ValidNumber == false)
{
// Ask the user for input
cout << "Please enter your phone number " << endl;
std::getline(cin, phoneNumber);
ValidNumber = true;
// Validate the phone number
for (std::string::iterator it = phoneNumber.begin(); it != phoneNumber.end();)
{
// Check for characters to ignore
if (*it == '(' || *it == ')' || *it == '-' || *it == ' ')
{
it = phoneNumber.erase(it);
}
// Check for numbers since we really want to keep them
elseif (*it >= '0' || *it <= '9')
{
++it;
}
// Check for invalid characters not removed
else
{
ValidNumber = false;
}
}
// phone number must have 10 digits
if (phoneNumber.size() != 10)
{
ValidNumber = false;
}
if (ValidNumber == false)
{
cout << "The phone number must have 10 digits.\n";
}
}
// Split the phone numbers
std::string areacode;
std::string prefix;
std::string number;
areacode = phoneNumber.substr(0, 3);
prefix = phoneNumber.substr(3, 3);
number = phoneNumber.substr(7, 4);
std::cout
<< "The properly formatted number is: ("
<< areacode
<< ") "
<< prefix
<< '-'
<< number
<< '\n';
return 0;
}
Why does it need to be so complicated? I'd start from scratch :)
Let the user type in whatever they like.
Store the input as a string.
Create a new string made up of only the digits.
Accept the string if it has 10 characters (digits).
Then apply the 'proper' formatting.
For the life of me I cant figure out how to copy the string but with only the digits. What I have now I've pieced together. and i'm so close this would work if it didn't delete the 7th digit for whatever reason...