2010-03-06 81 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

相关问题