1

I was wondering how I could convert an int to a string and then add it to an existin string. i.e.

std::string s = "Hello";
//convert 1 to string here
//add the string 1 to s

I hope I'm making sense. Thank you very much in advance for any answer.

5
  • Does ‘add’ mean append? Commented Jan 28, 2016 at 8:12
  • @Biffen Yes, english is not my mother tongue so, sorry. I want the new string to be "Hello1". Commented Jan 28, 2016 at 8:14
  • int i = 1; s.append(std::to_string(i)); Commented Jan 28, 2016 at 8:15
  • @Biffen: Nothing wrong with using "add" (talk to a Java guy). Although concatenation is a better word. Commented Jan 28, 2016 at 8:19
  • @Bathsheba No, nothing wrong, just wanted a clarification. Since numbers are involved, add could have a different meaning. Commented Jan 28, 2016 at 8:20

2 Answers 2

3

If the number you want to append is an integer or floating point variable, then use std::to_string and simply "add" it:

int some_number = 123;
std::string some_string = "foo";

some_string += std::to_string(some_number);

std::cout << some_string << '\n';

Should output

foo123
Sign up to request clarification or add additional context in comments.

3 Comments

I did that but I only get some random characters in the output. (% . , etc). (Along with the initial string of course)
@KostasKol Then you're doing something else wrong. The code in my answer works fine. If you don't get it to work, then create a Minimal, Complete, and Verifiable Example and show it in a new question, together with possible input, expected output and actual output.
could you believe I actually didn't see the <std::to_string(some_number)> part? I though I would just do <some_string += some_number>. It works! Thank you very much for the help.
2

The "modern" way is to use std::to_string(1). In fact, various overloads of std::to_string exist for different number types.

Putting this together you can write std::string s = "Hello" + std::to_string(1);

Alternatively you can use std::stringstream which can be faster due to fewer string concatenation operations which can be expensive:

std::stringstream s;
s << "Hello" << 1;
// s.str() extracts the string

1 Comment

Ok the std::to_string(1) did it. I also tried the stringstream one which seems better but I would have to make too many changes to my code just for one simple detail. At any rate, thank you very much. I really appreciate the help.

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.