/*// ********************************************************************** // // ** This file was downloaded from Jeff Heaton's Source Code Examples ** // // ** www.heat-on.com/source ** // // ********************************************************************** // // Copyright 1999 by Jeff Heaton // ********************************************************************** // // Permission is granted for royaltyfree use in compiled form. No // additional licensing is required. This code may not be distributed // in source form without written premission by Jeff Heaton. Generally // I will grant it. Just ask first. // // Basically I do not care how you distribute this code in compiled form. // But if your going to publish my source code somewhere I'd like to hear // about it first. // ********************************************************************** // // AddZeros V1.0// Written 1/22/1999 by Jeff Heaton// // AddZeros is a handy function to add leading zeros to C string. This // is very useful when you are storing some sort of a serial number in // a C based string. This function can handle ANY length string so long // as the input string is large enough to hold the number of zeros ask for */ #include #include /* // Function Name: AddZeros // Parameters: // str - Input string to add zeros to // zeros - How many leading zeros to add // Returns: // Nothing. // Purpose: // This function will modify str so that it contains the specified number // leading zeros. // Author // Jeff Heaton */ void AddZeros(char *str,int zeros) { char *source,*dest; if(strlen(str)>=zeros) return; /* Just the number is bigger than how many zeros you want */ dest=str+zeros-1; source=str+strlen(str)-1; while(source>=str) /* Move the org string to the right */ *(dest--)=*(source--); while(dest>=str)/* Fill in with zeros */ *(dest--)='0'; *(str+zeros)=0;/* Nul terminate the string */ } void main(void) { char str[80]; int zeros; printf("\nPlease enter a number>"); scanf("%s",str); printf("\nHow many leading zeros do you want>"); scanf("%d",&zeros); AddZeros(str,zeros); printf("Here it is: %s\n",str); gets(str); }