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+'      
5
  • ":" is not a std::string. Adding std::string and int probably doesn't do what you want. Commented Jun 4, 2015 at 18:28
  • 1
    @Yakk but "" is implicitly convertible to std::string. Commented Jun 4, 2015 at 18:29
  • @CaptainObvlious I don't see why that matters. The error is long before the =. Commented Jun 4, 2015 at 18:30
  • Use std::to_string or use a stringstream to concat integers to strings. Commented Jun 4, 2015 at 18:30
  • possible duplicate of C++ concatenate string and int Commented Jun 4, 2015 at 18:46

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.