如何在C ++中连接字符串和整数? [英] How do you concatenate strings and integers in C++?

查看:149
本文介绍了如何在C ++中连接字符串和整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  #includeTruck.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 =制造商名称:+名称+ +模型+,模型年:+年,里程:+英里;
return truckString;
}

我收到此错误:

 错误:对二进制表达式的操作数无效('basic_string< char,std :: char_traits< char>,std :: allocator< char>>'
'int')
string truckString =制造商名称:+名称+,型号名称:+ model +,型号年份:+ year,Miles ...



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

解决方案

在其他人提到的C ++ 03中,你可以使用 ostringstream >< sstream> :

  std :: ostringstream stream; 
stream< <混合数据,像这样int:< <137;
std :: string result = stream.str();

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

  std :: string result = fun:+ std :: to_string(137); 

希望这有助于!


I am trying to concatenate strings and integers as follows:

#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;
}

I am getting this error:

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

Any ideas what I might be doing wrong? I am new to C++.

解决方案

In C++03, as other people have mentioned, you can use the ostringstream type, defined in <sstream>:

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

In C++11, you can use the std::to_string function, which is conveniently declared in <string>:

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

Hope this helps!

这篇关于如何在C ++中连接字符串和整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆