2013-10-03 35 views
3

我試圖連接字符串和整數如下:如何在C++中連接字符串和整數?

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

+3

使用'std :: to_string'或一個sting流。 – chris

+0

@chris,我試着得到這個錯誤:錯誤:名字空間'std'中沒有名爲'to_string'的成員 – user1471980

+0

我今天早些時候遇到這個問題,發現取決於你的編譯器設置,你可能沒有訪問到'to_string'出於某種原因。查看stringstreams以便從'int'轉換爲'string':http://www.cplusplus.com/articles/D9j2Nwbp/ – TopGunCoder

回答

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

希望這會有所幫助!

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

s.str(); 
+0

請確保您的代碼具有四個空格縮進,或按CTRL + K自動縮進。否則,它將被解釋爲純文本。請參閱[格式化幫助](http://stackoverflow.com/help/formatting) – dyp

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