2010-03-06 82 views
5

我有一個字符串,我需要給它添加一個數字,即一個int。像:我如何添加一個int到一個字符串

string number1 = ("dfg"); 
int number2 = 123; 
number1 += number2; 

這是我的代碼:

name = root_enter;    // pull name from another string. 
size_t sz; 
sz = name.size();    //find the size of the string. 

name.resize (sz + 5, account); // add the account number. 
cout << name;     //test the string. 

這個工程...有點,但我只得到了 「名* 88888」 和...我不知道爲什麼。 我只需要一種方法來將int的值添加到字符串的末尾

+0

「我不知道爲什麼」。 「resize」的第二個參數是一個char,並且resize重複使用它來填充它在字符串末尾創建的任何額外空間。在你的情況下'account'等於56(mod 256),所以你已經傳遞了字符'8'。 – 2010-03-07 02:22:59

回答

4

使用stringstream

#include <iostream> 
#include <sstream> 
using namespace std; 

int main() { 
    int a = 30; 
    stringstream ss(stringstream::in | stringstream::out); 

    ss << "hello world"; 
    ss << '\n'; 
    ss << a; 

    cout << ss.str() << '\n'; 

    return 0; 
} 
+0

xD yay它運作Tyvm – blood 2010-03-06 19:57:46

5

沒有內置操作符可以執行此操作。您可以編寫自己的功能,爲stringint過載operator+。如果您使用自定義功能,請嘗試使用stringstream

string addi2str(string const& instr, int v) { 
stringstream s(instr); 
s << v; 
return s.str(); 
} 
+0

「沒有內置的運營商可以做到這一點。」我很失望。哦,我想他們不能想到*所有* ... – 2010-03-06 19:52:55

1

使用stringstream

int x = 29; 
std::stringstream ss; 
ss << "My age is: " << x << std::endl; 
std::string str = ss.str(); 
+0

或使用ostringstream是準確的。 – cpx 2010-03-06 19:52:21

4

您可以使用字符串流:

template<class T> 
std::string to_string(const T& t) { 
    std::ostringstream ss; 
    ss << t; 
    return ss.str(); 
} 

// usage: 
std::string s("foo"); 
s.append(to_string(12345)); 

或者您可以使用像增強lexical_cast()公用事業:

s.append(boost::lexical_cast<std::string>(12345)); 
0

可以使用lexecal_cast從提升,那麼C itoa當然stringstream的來自STL

相關問題