qazmlp wrote:
I have written the following code to extract the last 3 digits from a string.
Is there any improvement needed for this code?
-------------------
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
const char* nameWithID = "SOME_NAME_261" ;
char bufToHold3Digits[4] = {0} ;
strncpy( bufToHold3Digits , nameWithID + strlen( nameWithID ) - 3 , 3 ) ;
printf( "%d", atoi(bufToHold3Digits) ) ;
}
-------------------
You are doing both too little and too much work.
The "too little" part refers to defensive coding:
your technique will fail on input like "SOME_NAME_26"
and will fail even worse on input like "42". To guard
against such possibilities, you should check that
strlen(nameWithID) >= 3, and you should replace atoi()
with strtod() and use the error-checking it provides.
The "too much" refers to all that silly copying.
You *know* you're copying a three-character string, so
why not use strcpy() instead of strncpy(), avoiding the
need to pre-initialize bufToHold3Digits[] (using a form
C.B.F. thinks ought not to work). Better yet, why not
get rid of bufToHold3Digits[] altogether, and simply
apply strtod() to the final three characters of the
input string, right where they are?
A still more general approach might convert an
arbitrary number of trailing digits, not necessarily
three, enabling you to make sense of "SOME_NAME_1234".
Whether the greater generality is an "improvement" or
not depends on the wider context of the problem.
--
Er*********@sun.com