How to concatenate a std::string and an int?

前端 未结 23 2858
南方客
南方客 2020-11-22 02:40

I thought this would be really simple but it\'s presenting some difficulties. If I have

std::string name = \"John\";
int age = 21;

How do I

23条回答
  •  面向向阳花
    2020-11-22 03:20

    If you have Boost, you can convert the integer to a string using boost::lexical_cast(age).

    Another way is to use stringstreams:

    std::stringstream ss;
    ss << age;
    std::cout << name << ss.str() << std::endl;
    

    A third approach would be to use sprintf or snprintf from the C library.

    char buffer[128];
    snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
    std::cout << buffer << std::endl;
    

    Other posters suggested using itoa. This is NOT a standard function, so your code will not be portable if you use it. There are compilers that don't support it.

提交回复
热议问题