jake1138 said:
Here is a function I have to get a number at the end of a string.
Your function attempts to take all the numeric digits in the string
from left to right, not just the number the end of the string.
"number" as you say, implies both negative and positive variations.
I'm
posting this in case it proves helpful to someone. Comments are
welcome.
int getnum(char *str)
getnum's signature implies that it returns a number (positive or
negative) and takes a pointer to a modifiable stirng (although leaving
out 'const' is not a big deal).
You are hiding some peculiar "limits" to your function inside the
function. Where did/do you define BUFSIZE? What if the string is too
long, do you signal an error?
char *buf = buffer;
int i;
for (i = 0; i < BUFSIZE-1; i++) {
^^^^^
You are testing i, which is used to index into str not buffer, to
compare against BUFSIZE. This means, buf could still be pointing at
the beginning of your buffer (your buffer is empty) yet the limits of
the for loop can still be breached. You are limitting your function
greatly without need. Although you don't and shouldn't really use an
automatic char array in this situation, if for some reason you had to,
use some other index variable, like j, to point into buffer, and use
that to test against BUFSIZE (that way you know when exactly buffer is
filling up).
if (str == '\0') break;
if (!isdigit(str)) continue;
*(buf++) = str;
}
*buf = '\0';
There is no support for negative numbers or signs in your fuction. It
grabs all the numeric digits from left to right and plops it into a
limitted size array, which is actually not even limitted by it's own
use (see above) but rather by str's use.
if (buffer[0] != '\0') {
return atoi(buffer);
Where is atoi declared?
atoi has it's limitations, there are better functions for conversion
out there (strtol). Why don't you scan your string from right to left
with a pointer, wait until a non numeric value is reached, check the
next left char, if it's a - or +, move the pointer another unit left,
otherwise don't. Then you can pass this pointer into strtol and let it
do the conversion. Once that done, you should check for all types of
failure (associated with strtol/errno.h).
If and when you do add support for negative numbers, this return value
will add confusion. Better let the caller supply the address of some
variable, and use it to signal errors (or some other technique).
Take care