C++ 如何向字符串添加int
我有一个字符串,我需要向其中添加一个数字,即int。例如:C++ 如何向字符串添加int,c++,string,C++,String,我有一个字符串,我需要向其中添加一个数字,即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.re
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.
name=root\u enter;//从另一个字符串中提取名称。
大小(四);;
sz=name.size()//查找字符串的大小。
name.resize(sz+5,帐户);//添加帐号。
cout没有内置的操作符可以执行此操作。您可以编写自己的函数,为字符串和int重载运算符+
。如果使用自定义函数,请尝试使用stringstream
:
string addi2str(string const& instr, int v) {
stringstream s(instr);
s << v;
return s.str();
}
string addi2str(字符串常量和指令,int v){
弦流(仪表);
s
intx=29;
std::stringstream-ss;
ss
#包括
#包括
使用名称空间std;
int main(){
INTA=30;
stringstream ss(stringstream::in | stringstream::out);
ss您可以使用字符串流:
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));
你可以使用boost的lexecal\u cast
,然后是Citoa
,当然也可以使用STL的stringstream
,或者更准确地说,使用ostringstream。“没有内置的操作符可以做到这一点。”我很失望。哦,我想他们不能想到所有的事情……”我不知道为什么.resize
的第二个参数是一个字符,resize重复使用它来填充它在字符串末尾创建的任何额外空间。在您的情况下,帐户
等于56(mod 256),因此您传递了字符8
。
#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;
}
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));
s.append(boost::lexical_cast<std::string>(12345));