Hi
Let's say i have
char c = '2';
do anyone know how to get that 2 and store it in an int so that we have int x = 2 ??
Hi
Let's say i have
char c = '2';
do anyone know how to get that 2 and store it in an int so that we have int x = 2 ??
x = atoi(c);
atoi() takes char *, not char. Which is to say, it takes a string.
or if you really want to use atoi:Code:int x=c-'0';
Code:char tmp[]={c,0}; int x=atoi(tmp);
Ya but root4 can you explain why c-'0' is 2?? it just an operation on chars , why it gives an int??
A 'char' is an integer too but of a different size:
by definition sizeof(char)=1 byte, and on 32-bit systems, sizeof(int)=4 bytes.
Depending on the compiler, a char is signed or not.
I forgot to say a character is simply stored as a value, which interpretation
depends on the current 'encoding' (e.g. the value 65 means 'A' using the
ASCII encoding), hence c-'0'='2'-'0'=value for symbol '2' - value for symbol '0'=50-48=2
(digits and letters codes are sorted as expected, fortunately)
And are we supposed to know these values of the char 0 and 2 ?? because I'm a beginner And i didn't see these kind of things in class..
You don't have to know them, I gave the values above to explain why it works,
simply remember that if c is the code of a digit ('0'..'9') in any ASCII-compatible
encoding, then simply substract '0' to get the corresponding integer.
No, that's the whole point in writing something likeYou don't have to know what the value of '0' is in normal numbers - it happens to be 48 (0x30 (hex), 060 (octal) or 00110000 (binary)) in ASCII. Note that NOT all of the worlds computers uses ascii for numbers, but most do. Older style IBM machines (not PC's, but IBM mainframes and minicomputers) use something called EBCDIC, for example. I have no idea what '0' is in EBCDIC.Code:x = c - '0';
But for the purposes of number conversion, you need to know that 0 through 9 are consecutive, so you can always subtract '0' from a text-digit, and you have the corresponding integer value of that digit.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
Ok , thanks a lot