I want to make a number like 77 into a string but I can't use ascii because it's only from 0-9. Is there some way to make numbers become a string? So this is the result at the end: You input a number and it outputs the number but as a string. Example: input:123; output:"123".
Asked
Active
Viewed 155 times
-5
-
2`std::to_string` worth a try – pergy Oct 09 '17 at 13:32
-
This "number" will most-likely already be in the format of a string when the user inputs it. – byxor Oct 09 '17 at 13:32
-
[A good reference might help](http://en.cppreference.com/w/cpp/string/basic_string/to_string). – Some programmer dude Oct 09 '17 at 13:33
-
4_but i can't use ascii because it's only from 0-9_ Can you explain a bit more? – 001 Oct 09 '17 at 13:33
-
By the way, you should probably [read a couple of good beginners books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), because then you learn that a "string" is really nothing more than a collection of *single characters* (where each character could be a single digit, in whatever *character encoding* you want). – Some programmer dude Oct 09 '17 at 13:34
-
Well I want to use ascii but ascii can only go up to 9 so i think numbers with two digits can't use ascii – Dordor Oct 09 '17 at 13:34
-
@Dordor: But a string can have an arbitrary number of characters. – Bathsheba Oct 09 '17 at 13:35
-
Perhaps this will be elucidating: `std::string seven = std::to_string(7); std::string stringSum = seven + seven; std::cout << stringSum;` – Tom Blodget Oct 09 '17 at 17:00
2 Answers
2
Who said anything about ascii? The C++ standard doesn't.
Use the platform-independent std::to_string(77)
instead.
Reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string

Bathsheba
- 231,907
- 34
- 361
- 483
2
Each digit can use ASCII. The number 123 uses a 1, a 2, and a 3, and the string that represents that value uses the characters '1'
, '2'
, and '3'
.
The way to do the conversion yourself is to get each digit by itself and add the digit to '0'
. Like this:
int value = 123
std::string result;
while (value != 0) {
int digit = value % 10;
char digit_as_character = digit + '0';
result.insert(0, 1, digit_as_character);
value = value / 10;
}
This is pretty much what you'd do if you were doing it by hand:
- start with the value get the last digit of the value by dividing by 10 and looking at the remainder
- write down a digit for the remainder
- divide the value by 10 to remove the last digit, since you don't need it any more.

Pete Becker
- 74,985
- 8
- 76
- 165
-
Note that this works with any encoding supported by C++. Have an upvote. – Bathsheba Oct 09 '17 at 18:44
-
@Bathsheba — yes; I didn’t want to over-complicate this for a beginner. – Pete Becker Oct 09 '17 at 19:26