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

时间:2013-10-03 00:36:36

标签: 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;
}

我收到此错误:

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...

任何想法我可能做错了什么?我是C ++的新手。

3 个答案:

答案 0 :(得分:14)

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

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

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

std::string result = "Adding things is this much fun: " + std::to_string(137);

希望这有帮助!

答案 1 :(得分:2)

std::stringstream s;
s << "Manufacturer's Name: " << name
  << ", Model Name: " << model
  << ", Model Year: " << year
  << ", Miles: " << miles;

s.str();

答案 2 :(得分:2)

使用std::ostringstream

std::string name, model;
int year, miles;
...
std::ostringstream os;
os << "Manufacturer's Name: " << name << 
      ", Model Name: " << model <<
      ", Model Year: " << year <<
      ", Miles: " << miles;
std::cout << os.str();               // <-- .str() to obtain a std::string object