3

我正在尝试连接字符串和整数,如下所示:

#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++ 新手。

4

3 回答 3

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);

希望这可以帮助!

于 2013-10-03T01:07:46.160 回答
2
std::stringstream s;
s << "Manufacturer's Name: " << name
  << ", Model Name: " << model
  << ", Model Year: " << year
  << ", Miles: " << miles;

s.str();
于 2013-10-03T00:38:54.930 回答
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
于 2013-10-03T00:41:22.753 回答