用c ++格式化电话号码

use*_*910 0 c++

请协助,我正在尝试格式化电话号码(111)111-1111.我有以下代码,但我想写得更短.

int main(){

    string phone_number;

    cin >> phone_number;
    cout<<"(";

    for(int i = 0; i < 3; i++) {
      cout << phone_number[i];
    }

    cout << ")";
    for(int i = 3; i < 6; i++) {
      cout << phone_number[i];
    }

    cout << "-";

    for(int i = 6; i < 10; i++) {
      cout << phone_number[i];
    }

    cout<<endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

请协助

jro*_*rok 6

另一种可能性

cout << "(" << phone_number.substr(0,3) << ")"
     << phone_number.substr(3,3) << "-" << phone_number.substr(6,4) << endl;
Run Code Online (Sandbox Code Playgroud)


Mah*_*esh 5

使用string::insert。但是既然您将字符串作为输入,为什么不以您需要的格式提供输入。无论如何,如果您希望修改字符串,这就是无需任何循环即可完成的方法。如果您不想更改原始字符串,则将修改后的字符串存储到不同的临时变量中。

string phone_number = "123456789";
phone_number = phone_number.insert( 0, "(" );  // Original string is modified

// Rest can be achieved in similar fashion

cout << phone_number << endl;
Run Code Online (Sandbox Code Playgroud)