如何实现c ++电话号码格式:(000)-000-000?

时间:2017-02-18 19:47:10

标签: c++

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

std::wstring inputfield;

void function(uint32_t val)
{
    std::wstring keystring;
    keystring = std::to_wstring(val);    
    inputfield = inputfield + keystring; 
    std::wstringstream s;
    s << L"(" << inputfield << L") ";
    std::wstring str = s.str();
    std::wcout << str << "\n";
    return;
}

int main()
{
    uint32_t x ;
    while(cin>>x)
    {
        function(x);
        cout<< *(&x)<< endl;
    }
    return 0;
}

我正在尝试使用字符串格式来获取类似(000)-000-000或USA phonenumber格式的输出,但我无法实现,请帮助,谢谢

3 个答案:

答案 0 :(得分:2)

如果你想改变字符串000000000或者simillar(即使输入是一个数字,只需将其转换为std::to_string),那么只需在适当的位置添加几个字符。

std::string format_number(std::string str) {
    if(str.size() != 9) {
        throw std::logic_error{"Phone number is not 9-characters long"};
    }

    str.insert(str.begin(), '(');
    str.insert(str.begin() + 4, ')');
    str.insert(str.begin() + 5, '-');
    str.insert(str.begin() + 9, '-');

    return str;
}

答案 1 :(得分:0)

您可以分配输入电话号码,然后传递这样的结构;

struct numbers {     
     int A;
     int B;
     int C;
} // then get (A)-B-C 

答案 2 :(得分:0)

#include <iostream>
#include <thread>
#include <string>
//---- The following function will be invoked by the thread library
void thread_proc(std::string msg)
{
    std::cout << "ThreadProc msg:" << msg;
}
int main()
{
    // creates a new thread and execute thread_proc on it.
    std::thread t(thread_proc, "Hello World\n");
    // Waiting for the thread_proc to complete its execution
    // before exiting from the program
    t.join();
}  



How to resolve this error
  $ g++ Dummy.cpp -o Dummy -std=c++1z -pthread
    Dummy.cpp: In function 'int main()':
    Dummy.cpp:12:10: error: 'thread' is not a member of 'std'
       12 |     std::thread t(thread_proc, "Hello World\n");
          |          ^~~~~~
    Dummy.cpp:3:1: note: 'std::thread' is defined in header '<thread>'; did you forget to '#include <thread>'?
        2 | #include <thread>
      +++ |+#include <thread>
        3 | #include <string>
    Dummy.cpp:15:5: error: 't' was not declared in this scope; did you mean 'tm'?
       15 |     t.join();
          |     ^
          |     tm