The conversion is the easy part...
But if you must not use library functions,
- there is only one way to take a string, and that is
argv
;
- there is only one way to give an integer, and that is the exit code of the program.
So, without much ado:
int main( int argc, char * argv[] )
{
int rc = 0;
if ( argc == 2 ) // one, and only one parameter given
{
unsigned i = 0;
// C guarantees that '0'-'9' have consecutive values
while ( argv[1][i] >= '0' && argv[1][i] <= '9' )
{
rc *= 10;
rc += argv[1][i] - '0';
++i;
}
}
return rc;
}
I did not implement checking for '+'
or '-'
, and did not come up with a way to signal "input is not a number". I also just stop parsing at the first non-digit. All this could probably be improved upon, but this should give you an idea of how to work around the "no library functions" restriction.
(Since this sounds like a homework, you should have to write some code of your own. I already gave you three big spoons of helping regarding argv
, the '0'-'9'
, and the conversion itself.)
Call as:
<program name> <value>
(E.g. ./myprogram 28
)
Check return code with (for Linux shell):
echo $?
On Windows it's something about echo %ERRORLEVEL%
or somesuch... perhaps a helpful Windows user will drop a comment about this.
Source for the "'0'-'9'
consecutive" claim: ISO/IEC 9899:1999 5.2.1 Character sets, paragraph 3:
In both the source and execution basic character sets, the value of each character after 0
in the above list of decimal digits shall be one greater than the value of the previous.
I'm sure this is preserved in C11, but I only have the older C99 paper available.