I want to convert a char type '9' to its real integer value, 9, and not the ascii code, so how do i do this?
Printable View
I want to convert a char type '9' to its real integer value, 9, and not the ascii code, so how do i do this?
The atoi() function.Code:#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int n;
char *str = "12345.67";
n = atoi(str);
printf("string = %s integer = %d\n", str, n);
return 0;
}
Yeah that great for const char.... but say
i have...
char g;
g = '5';
how do i get the integer value (5) from g?
well somehow i managed to pull it off...
int s;
char e = '5';
char g = '0';
s = e-g;
that works for some strange reason....
Like this:
Code:int s = atoi(q)
char c;
c = '5';
int i=c-48;
I think kedaman's way is the better way if your number is always a single digit. Faster also.
The standard way in C to get an integer value from a string is the ascii to integer function atoi().
Don't go messing with char artihmetic operations. Plus, the default for most compilers is signed char, which will also get you in even more trouble with char arithmetic operations.
nemaroller run this code and you see why it works, and why shouldn't do it that way.
Code:#include <iostream.h>
void main()
{
char a = '5';
char b = '0';
int c = a - b;
cout << (int)a << endl
<< (int)b << endl
<< c << endl << endl;
c = a + b;
cout << (int)a << endl
<< (int)b << endl
<< c << endl;
}
f**k the standard, C++ is lowlevel as much as highlevel, and chars aren't C-strings if you stand by your definitions. char is as much a integer as a C-string, depends in what context you use it.Quote:
Originally posted by jim mcnamara
The standard way in C to get an integer value from a string is the ascii to integer function atoi().
Don't go messing with char artihmetic operations. Plus, the default for most compilers is signed char, which will also get you in even more trouble with char arithmetic operations.
besides, atoi will f**k you if next byte in memory isn't a nullchar
if you want to be explicit about datatypes:
char c;
c = '5';
int i=(int)c-48;