字符串与数组问题:C++电话号码格式化程序运行异常
Hey there! Let's get that C++ phone number formatter up and running smoothly in Visual Studio. I’ll share a working implementation that aligns with your requirements, plus break down the common pitfalls that might have been causing your errors.
Working Implementation
Here’s a complete program that handles input filtering, validation, and standard formatting exactly as you described:
#include <iostream> #include <string> #include <cctype> using namespace std; int main() { string userInput; string cleanedDigits; // Read the entire input line (critical for handling spaces/symbols) cout << "Enter a phone number (can include hyphens, parentheses, etc.): "; getline(cin, userInput); // Step 1: Strip out all non-digit characters for (char c : userInput) { if (isdigit(static_cast<unsigned char>(c))) { // Cast to avoid undefined behavior for negative chars cleanedDigits += c; } } // Step 2: Check if we have enough digits if (cleanedDigits.size() < 10) { cout << "Error: Not enough digits provided. Please enter at least 10 numeric digits." << endl; return 1; } // Step 3: Truncate to first 10 digits if there are extra if (cleanedDigits.size() > 10) { cleanedDigits = cleanedDigits.substr(0, 10); } // Step 4: Format and print the standard phone number cout << "Formatted number: (" << cleanedDigits.substr(0, 3) << ") " << cleanedDigits.substr(3, 3) << "-" << cleanedDigits.substr(6, 4) << endl; return 0; }
Why Your Original Code Might Have Failed
Chances are, you ran into one of these common issues in Visual Studio:
- Using
cin >> userInputinstead ofgetline: The>>operator stops reading at the first whitespace or non-alphanumeric character, so if your input had spaces (like "123 456 7890") or symbols, it would only capture part of the input, leading to missing digits or unexpected behavior. - Forgetting to include
<cctype>: Theisdigitfunction requires this header; without it, you might get compiler errors or undefined runtime behavior. - Not handling negative
charvalues: Some systems storecharas signed, so passing a negative value toisdigitis undefined. Casting tounsigned charfixes this.
How to Run in Visual Studio
- Create a new Console App project in Visual Studio.
- Replace the default
main.cppcode with the snippet above. - Build and run the project. Test inputs like
(555) 123-4567,555-987-6543 ext 101, or555123456to see it work.
内容的提问来源于stack exchange,提问作者Meh
相关产品推荐
相关产品推荐

