You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

字符串与数组问题: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 >> userInput instead of getline: 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>: The isdigit function requires this header; without it, you might get compiler errors or undefined runtime behavior.
  • Not handling negative char values: Some systems store char as signed, so passing a negative value to isdigit is undefined. Casting to unsigned char fixes this.
How to Run in Visual Studio
  1. Create a new Console App project in Visual Studio.
  2. Replace the default main.cpp code with the snippet above.
  3. Build and run the project. Test inputs like (555) 123-4567, 555-987-6543 ext 101, or 555123456 to see it work.

内容的提问来源于stack exchange,提问作者Meh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:57:04