如何连接字符串和整数

How to concatenate a string and an integer

在编译时我无法连接 string.I 我有点困惑我如何 concatenate.I 尝试进行类型转换然后连接,但这也会引发错误。

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

string whatTime(int n)
{
    int h=n/3600;
    int m=n/60;
    int s=n%60;

    string s1=h + ":" + m + ":" + s;
}

int main()
{
    string s=whatTime(63);
    cout<<s;
    return 0;   
}

我遇到了错误

invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'      

您可以使用 std::to_string 从您的 int

创建 std::string
string s1 = std::to_string(h) + ":" + std::to_string(m) + ":" + std::to_string(s);

记住你必须从你的函数中 return

string whatTime(int n)
{
    int h = n / 3600;
    int m = n / 60;
    int s = n % 60;

    return to_string(h) + ":" + to_string(m) + ":" + to_string(s);
}

我的字符串不擅长做这些。在添加到字符串之前必须将数字转换为字符串。 CoryKramer 打字速度更快。我用流显示其他方式。必须包含 sstream。

stringstream stream;
stream << h << ":" << m << ":" << s;
return stream.str();