How do you concatenate strings and integers in C++?

18,917

Solution 1

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!

Solution 2

Use 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

Solution 3

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

s.str();
Share:
18,917
user1471980
Author by

user1471980

Updated on June 04, 2022

Comments

  • user1471980
    user1471980 almost 2 years

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