How does one parse an integer to string(char* || char[]) in C? Is there an equivalent String parseInt(int) method from Java in C?
If you want to convert an integer to string, try the function snprintf()
.
If you want to convert a string to an integer, try the function sscanf()
or atoi()
or atol()
.
The Java parseInt()
function parses a string to return an integer. An equivalent C function is atoi()
. However, this doesn't seem to match the first part of your question. Do you want to convert from an integer to a string, or from a string to an integer?
You can also check out the atoi()
function (ascii to integer) and it's relatives, atol
and atoll
, etc.
Also, there are functions that do the reverse as well, namely itoa()
and co.
To convert an int to a string:
int x = -5;
char buffer[50];
sprintf( buffer, "%d", x );
You can also do it for doubles:
double d = 3.1415;
sprintf( buffer, "%f", d );
To convert a string to an int:
int x = atoi("-43");
See http://www.acm.uiuc.edu/webmonkeys/book/c_guide/ for the documentation of these functions.
It sounds like you have a string and want to convert it to an integer, judging by the mention of parseInt
, though it's not quite clear from the question...
To do this, use strtol
. This function is marginally more complicated than atoi
, but in return it provides a clearer indication of error conditions, because it can fill in a pointer (that the caller provides) with the address of the first character that got it confused. The caller can then examine the offending character and decide whether the string was valid or not. atoi
, by contrast, just returns 0 if it got lost, which isn't always helpful -- though if you're happy with this behaviour then you might as well use it.
An example use of strtol
follows. The check for error is very simple: if the first unrecognised character wasn't the '\x0'
that ends the string, then the string is considered not to contain a valid int.
int ParseInt(const char *s,int *i)
{
char *ep;
long l;
l=strtol(s,&ep,0);
if(*ep!=0)
return 0;
*i=(int)l;
return 1;
}
This function fills in *i with the integer and returns 1, if the string contained a valid integer. Otherwise, it returns 0.
You may want to take a look at the compliant solution on this site.