加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:40:51 所属栏目:百科 来源:网络整理
导读:参见英文答案 How to concatenate a std::string and an int?????????????????????????????????????29个 我试图连接字符串和整数如下: #include "Truck.h"#include string#include iostreamusing namespace std;Truck::Truck (string n,string m,int y){ na
参见英文答案 > How to concatenate a std::string and an int?????????????????????????????????????29个
我试图连接字符串和整数如下:

#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 + ",Miles...

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

解决方法

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

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

希望这可以帮助!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读