如何在字符串中添加整数? [英] How to add integer in a string?
本文介绍了如何在字符串中添加整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用字符串值而不是变量附加整数值.
I want to append integer value with string value but not a variable.
我试图将一个整数值放入一个名为二月的字符串中.我用 += 操作符试过了,但没有用.
I tried to put an integer value which is variable with a string called February. I tried it using += operator but it did not work.
string getMonth(day)
{
if(day >=31 ){
day -= 31;
"February "+=day;
}
}
推荐答案
做类似的事情
#include <string>
// ...
std::string s( "February " );
s += std::to_string( day );
这是一个演示程序
#include <iostream>
#include <string>
int main()
{
std::string s( "February " );
int day = 20;
s += std::to_string( day );
std::cout << s << '\n';
}
它的输出是
February 20
另一种方法是使用字符串流.
Another approach is to use a string stream.
这是另一个演示程序.
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::ostringstream oss;
int day = 20;
oss << "February " << day;
std::string s = oss.str();
std::cout << s << '\n';
}
其输出与上图相同.
这篇关于如何在字符串中添加整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文