473,395 Members | 1,488 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Code for substring & int conversion

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) ) ;
}
-------------------
Nov 14 '05 #1
3 3032
On Tue, 26 Oct 2004 12:03:33 -0700, 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? Not really. There would be amazingly many ways of achieving the same
though. If needed you might anticipate there to be more or less than 3
digits, e.g. an implementation would find the last '_' and take everything
from there to eol.

for just 3 digits, a shorter might be:
const char* nameWithID ="SOME_NAME_261";
const char *last3; last3 = nameWithID +(strlen(nameWithID)-3);
printf( "%d",atoi(last3));

-------------------
#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) ) ;
}
-------------------


Nov 14 '05 #2
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

Nov 14 '05 #3

"qazmlp" <qa********@rediffmail.com> 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) ) ;
}

The most important thing is that code should be reusable. So you need to
make the process into a function.

/*
gets the last three digits of a string
Params: out - pointer to output (must be at least 4 characters long)
in - pointer to input string
Notes: As Eric Sosman pointed out, what happens if the input has less than
three characters? What if the last three characters are not decimal
digits.
What happens if you are passed NULL?
There are not necessarily any right answers to these questions, but
you
need to think about them.
*/
void last3digits(char *out, const char *in)
{
/* code goes here */
}

The other problem is that the test is lousy. You need to recompile for every
test.

Try this

int main(int argc, char **argv)
{
char buff[4];
if(argc == 2)
{
last3digits(buff, argv[1]);
printf("Last 3 digits %s\n", buff);
}
else
printf("Call with an argument string\n");

return 0;
}
Nov 14 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: bdinmstig | last post by:
I refined my attempt a little further, and the following code does seem to work, however it has 2 major problems: 1. Very limited support for XPath features Basic paths are supported for...
27
by: Daniel Vallstrom | last post by:
I'm having problems with inconsistent floating point behavior resulting in e.g. assert( x > 0.0 && putchar('\n') && x == 0.0 ); holding. (Actually, my problem is the dual one where I get...
1
by: Egbert Nierop \(MVP for IIS\) | last post by:
Hi, I'm 'improving' CComBSTR (yes, I do still program unmanaged code in addition to C# ) to contain features, not found in it. Does anybody have good code which maches LastIndexOf()? If...
7
by: Rich Grise | last post by:
OK, I don't know if this is Off-Topic for the group(s), because "QT" isn't "Pure C++", and Slackware is a distro, but those guys are sharp. :-) And I've crossposted to sci.electroncs.design because...
8
by: Eric Lilja | last post by:
Hello, I have IPv4-numbers in the following format: "\\x0A\\x11\\x8C\\x01" Now I need each byte as an int. I wrote the following test program: #include <stdio.h> #include <stdlib.h> static...
9
by: scriptguru | last post by:
I've found some funny pieces of code in one project... I don't know: to laught or to cry =) function toHex(decimal) { switch(decimal) { case 10: return "A"; case 11: return "B"; case 12:
2
by: coder_lol | last post by:
MS VS 7.0 happily resolves by SmartPointer and Inheritance, but I got to use another target compiler and it does not accept user conversion for templates. Can I forced a recast somehow? I have...
3
by: Dhananjay | last post by:
Hi All, I am facing problem when i am converting C#.net code(Delegate concept) into vb.net. I am unable to do that . Can someone help me to solve the problem. I am providing my C#.net code. ...
2
by: sophia | last post by:
why scanf("%d. %d. %d",&d,&m,&y); is NOT reading the i/p 22 4 1972 correctly, whereas it is reading the i/p 22. 4. 1972 correctly ?. Is it because of the dot in the format string of scanf ?
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.