How can one convert an int to a char in C?
-
For example in c: char str [] ="10000"; int n =str [3]; n=n-48; n=n+3; str [3] =n; This one is not working. Why?
-
Answer:
Please see for reference the wonderful essay linked here: http://www.catb.org/~esr/faqs/smart-questions.html. There is one thing missing, "what exactly doesn't work". It doesn't do what it's supposed to do? Or it doesn't mean what you wanted it to do? My guess is that once you run the program you will get exactly the expected result: "100" followed by character with ASCII code 3, followed by '0'. I also suggest using n=n-'0'; instead of n=n-48;, as it makes your intention clearer.
Dorin LazÄr at Quora Visit the source
Other answers
I believe the example you provided should work as you would expect. Most of it is unnecessary though. Adding 3 to an element on 3rd index is as simple as: #include <stdio.h> int main() { char str[] = "10000"; str[3] += 3; printf("%s\n", str); return 0; } But keep in mind that when number on 3rd index is larger than 6, you'll get garbage instead of sensible output.
Stepan Bujnak
Use "itoa" function. char * itoa ( int value, char * str, int base ); value : Value to be converted to a string. str: Array in memory where to store the resulting null-terminated string. base: Numerical base used to represent the value as a string, between 2 and 36, where 10 means decimal base, 16 hexadecimal, 8 octal, and 2 binary. It should work for you.
Paras Vishnoi
Related Q & A:
- How can I convert Matlab code to c#?Best solution by Stack Overflow
- How can I convert a string number to a number in Perl?Best solution by Stack Overflow
- How can I convert a video to mp3 format?Best solution by Yahoo! Answers
- How can one start a non-profit organization?Best solution by Yahoo! Answers
- How can i convert a game on my old pc to my new pc?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.