--- In [email protected], "siddhiruhi011" <siddhiruhi...@...> wrote:
>
> ...we can use library functions to convert character string
> into integer variable but we can write our own function
In other words, we can use trusted source that's (generally)
been rigorously tested, or we can reinvent the wheel to be
a square with no tyres...
> like the following one which is compiled using Turbo C
Oh dear. You're using Turbo C.
>
Where are your headers? Not that I have much desire to
know, but if I ever went insane and decided to install
Turbo C, it may be useful to know where all the non-
standard functions are declared...
> int main()
> {
> char *str;
> int cnt;
> clrscr();
...functions like this one.
Check out the links section of C-Prog and get yourself a
more up to date toolset.
> gets(str);
First: NEVER USE GETS()! EVER!!
Second: You haven't allocated any storage for the string,
only an uninitialised pointer.
Third: What if the input stream has an end of file? Check
the return value of input functions.
> printf("%s\n",str);
With all the negatives, I should congratulate you on
terminating the line of text with a newline. [Although,
I'd simply have written puts(str).]
> cnt=chng(str,5);
What if the user enteres 0? The string would consist of a
'0' and a null byte, yet you ask chng to convert 5
characters.
Additionally, the problems associated with unprototyped
functions are well known and have been for decades. Declare
your functions.
> printf("%d\n",cnt);
> getch();
Another non-standard function. "If you are going to do this
damn silly thing..." what's wrong with getchar()?
> return 0;
> }
>
> int chng(char *tmp,int no)
Better is...
int chng(const char *tmp)
The string is not modified, and there's no obvious reason why
you supply a length. If you have to have one, then size_t is
preferable to int.
> {
> char ch1;
> int j,cng=0,cngs=0;
You have identifiers called chng, cng and cngs. I wouldn't
want to maintain this code.
> for(j=0;j<no;j++)
And if the string is smaller than 'no' characters?
> {
> ch1=tmp[j];
Put the character in a temporary variable...
> cng=(int)ch1;
Put the same value in another temporary variable, using
a redundant cast...
> cng&=0x0f;
Mask the bottom 4 bits of the character code...
> cngs+=cng;
Add it to yet another temporary variable.
> if(j!=no-1)
> cngs*=10;
This entire loop body could be replaced with...
cngs = cngs * 10 + (tmp[j] & 0xf);
...making the whole process at least decipherable at a
glance, even if it doesn't actually convert an entered
string into the number hoped for.
> }
> return cngs;
> }
>
> if there is some problem please let me know.
There are many problems.
--
Peter