gpt4 book ai didi

c++ - 在 C++ 中格式化电话号码

转载 作者:太空宇宙 更新时间:2023-11-04 14:42:32 25 4
gpt4 key购买 nike

请协助,我正在尝试格式化电话号码,如 (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;
}

请帮忙

最佳答案

另一种可能性:

cout << "(" << phone_number.substr(0,3) << ")"
<< phone_number.substr(3,3) << "-" << phone_number.substr(6,4) << endl;

关于c++ - 在 C++ 中格式化电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7786383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com