I am currently reading a program that uses this:
int a = atoi(array_name);
I know that this method returns a int from a char array, but I don't understand. How can this method pull out one int when we have several char entries?
I am currently reading a program that uses this:
int a = atoi(array_name);
I know that this method returns a int from a char array, but I don't understand. How can this method pull out one int when we have several char entries?
By figuring out what each character is worth, and adding/multiplying that into the whole number.
E.g. we have the char array with '1', '7', '3' (and a terminating zero '\0').
It then finds '1', which is our hundreds, '7' as our tens, and '3' as the units. So the final number is 173.
--
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.
So this method performs some operations to find this number?
Yes. Namely:
- Subtraction (to convert the character value from the ascii [or whatever character set it may be] into a single digit integer value, e.g '1' to 1, '7' to 7 and '3' to 3 in the above case].
- Addition to add the current digit to the final result.
- Multiplication so that the digits position corresponds to it's value.
Now, here's a question for you to ponder: Without asking on a forum, can you figure out how to do the above, WITHOUT knowing how many digits the number is - that is, you only know that you have between 1 and 9 digits [so it fits nicely in an integer], that are terminated by a zero-character ('\0'). It is not hard, but most people tend to try to multiply by 100 for the hundreds digit, 1000 for the thousands digit, and such. This means that you need to know what each digit represents [which in turn means that you need to know how many digits the number has]. It is not hard to solve WITHOUT knowing the length, but it takes a bit of "lateral thinking" to come up with the answer.
--
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.
Thank you sir!