如何在C++中连接字符串和整数?

use*_*980 3 c++ string type-conversion

我试图连接字符串和整数如下:

#include "Truck.h"
#include <string>
#include <iostream>

using namespace std;

Truck::Truck (string n, string m, int y)
{
    name = n;
    model = m;
    year = y;
    miles = 0;
}

string Truck :: toString()
{

    string truckString =  "Manufacturer's Name: " + name + ", Model Name: " + model + ", Model Year: " + year ", Miles: " + miles;
    return truckString;
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

error: invalid operands to binary expression ('basic_string<char, std::char_traits<char>, std::allocator<char> >'
      and 'int')
        string truckString =  "Manufacturer's Name: " + name + ", Model Name: " + model + ", Model Year: " + year ", Miles...
Run Code Online (Sandbox Code Playgroud)

我有什么想法可能做错了吗?我是C++的新手.

tem*_*def 14

在C++ 03中,正如其他人所提到的,您可以使用以下ostringstream定义的类型<sstream>:

std::ostringstream stream;
stream << "Mixed data, like this int: " << 137;
std::string result = stream.str();
Run Code Online (Sandbox Code Playgroud)

在C++ 11中,您可以使用该std::to_string函数,该函数在<string>:

std::string result = "Adding things is this much fun: " + std::to_string(137);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!