1

On compiling I am not able to concatenate the string.I am a little confused as to how do I concatenate.I tried to typecast and then concatenate,but that too throws an error.

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

I am getting the error

invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'      
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
Kunal Sehegal
  • 63
  • 1
  • 5

2 Answers2

3

You can use std::to_string to create std::string from your int values

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

Remember you have to return from your function!

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);
}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

Me string not smart enuf to do dat. Must turn number to string before add to string. CoryKramer type faster. I show other way with stream. Must include sstream.

stringstream stream;
stream << h << ":" << m << ":" << s;
return stream.str();
user4581301
  • 33,082
  • 7
  • 33
  • 54