Question:
In C++ how do I convert an int to a C-style string?
1970-01-01 00:00:00 UTC
In C++ how do I convert an int to a C-style string?
Four answers:
weeks
2016-10-04 07:54:02 UTC
C++ I controlled to circumvent as a consequence a approaches, yet i think of AM positioned up's is right. Make myCalc an unsigned int. i don't be responsive to what number bytes an int form in C++ is, yet for the sake of representation, we could say that's a million byte. An unsigned int can take on the values 0..255 Int would properly be -128..0..127. of course you could not stuff an insigned int into an int. the form solid won't be ready to instruct you a thank you to given which you run into the comparable project. it won't be ready to map the stupid issues. -Dio
Cool Story Bro
2011-04-06 19:35:20 UTC
C doesn't have "String" type strictly speaking. It has char arrays instead.



Just use the itoa() function that will return a char array which will have each digit of the number stored in a new index of the array.

Also itoa returns a NULL-TERMINATED STRING, so it saves you from that hassle :)



PS: I believe you are familiar to char[] types. But just a reminder:

You can't access the entire "string" by saying just using the array's name. Array name is just a pointer to index 0 of the array as you can guess.

But you can still use puts(); and "%s" for char[] types.
Fredmaster
2011-04-06 19:25:06 UTC
Just use the itoa() function.
The Phlebob
2011-04-06 19:28:21 UTC
Consider that the remainder left by dividing an int by 10 (decimal) is the binary value of that particular decimal digit. Add the appropriate value to convert to ASCII ('0'), and you have the display digit. Then divide the original value by 10 (decimal) and use the quotient for the next cycle. Stop when the quotient is zero.



Yes, you do need to put a null at the end. I suggest you fill number_string[] with them before even starting the conversion.



I think this is known as a "cascading polynomial" by the way. A similar method is used to convert ASCII to an int.



Hope that helps.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...