How to convert a char array into an int in C++?

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

Was this solution helpful to you?

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:

Just Added Q & A:

Find solution

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.