如何在字符串中添加整数?

How to add integer in a string?

我想将整数值附加到字符串值而不是变量。

我试图输入一个整数值,它是可变的,带有一个名为 February 的字符串。我尝试使用 += 运算符,但没有用。

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

另一种方法是使用字符串流。

这里还有一个演示程序。

#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';
}

其输出与上图相同

上面的答案解决了我的问题。如果你像我一样使用dev c++那么你可能会遇到同样的问题,我建议你添加-std=c++11。为此,您可以转到 link How to change mode from c++98 mode in Dev-C++ to a mode that supports C++0x (range based for)? 并转到第二个答案。谢谢