How do I convert an integer to a string?

Hello, I’m making a project in C++ that I’ll be releasing in Christmas, but there’s a problem.

I don’t really know how to convert integers to strings. And this is strongly required in my project.

I know there’s the to_string method, used like this:

int someInput;
std::cout << "I need a name! ";
std::cin >> someInput;
std::to_string << "Hi, I'm " << someInput << "\n";

But that’s not really useful for me, as I need the input inputted first, and not outputed right away.
Please help!

2 Likes

Did you mean to write,

std::cin >> someInput;

?

3 Likes

Oh whoops, sorry. I’ll edit that.

3 Likes

i beleave you can use to_string like this

std::to_string(someInput)

so if you are trying to save you’re input as a string as soon as it comes in, this might work ?

std::cin >> std::to_string(someInput);

http://www.cplusplus.com/reference/string/to_string/

3 Likes

Oh my goodness, I never thought about chaining like that! Thank you so much :smile:

2 Likes

Could be wrong but I don’t see that as ‘chaining’. std is not a method.

In JavaScript, this would be chaining…

String.toLowerCase().split(' ').join('*')

object.method.method.method

That is method chaining.

3 Likes

The chaining I meant was this:

std::cout << "Your answer is this: " << std::to_string(answer) << "." << "\n";
3 Likes

Ah, that makes sense. D’oh!

3 Likes