If you want to convert a C-string (zero-terminated array of chars) of digits, you can call one of the library functions to do this (good idea), or write something like the following (good exercise).
Every character is represented by a pattern of bits. These patterns can be thought of as integers. If your system uses ASCII (or any of the newer standards), the integer value of the code for '0' is 48, '1' is 49, etc. This knowledge is commonly used when converting character digits to their equivalent values.
One of the problems to solve immediately is what to do with errors. Let's make this a bool function that returns true if we can convert the string (eg, no illegal characters), and false otherwise. We'll pass the value back in a reference parameter.
//============================================== string2int bool string2int(char* digit, int& result) { result = 0; //--- Convert each digit char and add into result. while (*digit >= '0' && *digit <='9') { result = (result * 10) + (*digit - '0'); digit++; } //--- Check that there were no non-digits at end. if (*digit != 0) { return false; } return true; }
A shorter, but perhaps less readable, version can replace the last three statements to return the correct bool value. Recent compilers should produce equivalently efficient code, so the most important thing is to choose the most readable version. In general try to resist making programs shorter without improving their clarity. The following is plausible, and may be more readable.
return *digit == 0; // true if at end of string.
A more extreme shortening is definitely NOT more readable.
bool s2i(char*d,int&r){for(r=0;*d>='0'&&*d<='9';r=r*10+*(d++)-'0');return*d==0;}
Solution: See Solution: C-string to double for a solution to some of these exercises.