连接字符串和整数

连接字符串和整数

This question already has answers here:
How to concatenate a std::string and an int

(24 个回答)


7年前关闭。




我正在尝试按如下方式连接字符串和整数:
#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++ 的新手。

最佳答案

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

希望这可以帮助!

关于c++ - 你如何在 C++ 中连接字符串和整数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19149022/

10-12 01:33