Write a function that takes a string as input, and checks if it is a valid U.S. phone number, and returns a string with just the digits. A valid phone number maybe start with some white space, has 3 digits followed optionally by a hyphen possibly surrounded by white space, then 3 more digits, another hyphen possibly surrounded by whitespace, and finally 4 digits followed by whitespace. If the input string isn’t valid, an error message should be displayed. If the string is valid it should pass out through an output argument a string with just the 10 digit phone number.
Also, am I using bool correctly?
You should probably look into regular expressions. That's the best way to do that.
What are regular expressions? I kind of just want to learn the basic way to do it using strings. I can just use class processing functions right?
Thomas, I'm not replacing certain how to how to use replace because in strings spaces count, so what if the user inputs 555 - 555 - 5555? Unless of course in the problem, I am assuming there hyphen is located in between exactly two spaces?
you can remove all spaces one by one
What do you mean? Can you give me a random example? Also I edited my code. Can you let me know why the way I did it doesn't work?
#include<iostream> #include<string> #include<cctype> int numberChecker(int phoneNumber) { string number; if (isdigit(number)) return phoneNumber; } using namespace std; int main() { int phoneNumber; string number; cout << "Enter a valid phone number: " << endl; cin >> number; if ( number.length() == 10) { return true; } else { cout << numberChecker(phoneNumber) << endl; } return 0; }
It keeps giving me an error about string number not being declared in the function but it is :( ??? Am I declaring it wrong?
cout << numberChecker(phoneNumber) << endl; you didn't assign any value to phoneNumber variable
int numberChecker(int phoneNumber) { string number; if (isdigit(number)) return phoneNumber; } you didn't assign any value to number here too, and you better use diffferent names for functions
What do you mean by different names for functions and the value to the number is the user input cin? :( Perhaps, I'm missing something fundamental
cin >> number; you input into variable named number you want access function with variable phoneNumber which is empty cout << numberChecker(phoneNumber) << endl;
just use grep
Is it C ?
^C++
Join our real-time social learning platform and learn together with your friends!