Re: Help with atoi function for a numero program.
- From: Ben Bacarisse <ben.usenet@xxxxxxxxx>
- Date: Fri, 30 May 2008 23:24:51 +0100
Ram <sriram.n83@xxxxxxxxx> writes:
I'll just make a few remarks...
printf ("Enter your name (ONLY CAPITAL LETTERS) :- ");
fgets (name,BUFSIZE,stdin);
Why make the user do the work? Computers are good at this short of
thing. Either convert the letter after you read them...
ch=name[i];
count=((ch-'A')%9)+1;
Or do it here.
sub_sum=sub_sum+count;
I'd write: sub_sum += (toupper(name[i]) - 'A') % 9 + 1;
for ( i=0; str[i]!='\0'; i++)
{
tmp[0]=str[i];
c=atoi(tmp); // I need help here
cnt=cnt+c;
}
cnt += str[i] - '0'; but see below...
printf ("Count is the value of sum of the two integers %d\n",cnt);
if ((cnt > 9) && (cnt != 11) && (cnt != 22))
{
continue;
}
else
{
res += cnt;
sub_sum=0;
break;
}
This is probably over complex. The pattern you have is:
while (C) {
/* some stuff */
if (C)
continue;
else {
/* a little more */
break;
}
}
If you get the loop body right, all you need is a while. No need to
repeat the test in the middle.
}
}
}
printf("The sum of the words are %d\n",res);
// The code is incomplete i have to again do a sum of res if that
turns to be a double digit and then check if // the final result will
be <9 or == 11 or == 22 and if this is fine then pass it to switch
case to get me the corresponding characteristics of the name.
}
General points: use a little more horizontal space. Breaking
the problem into helpful functions will make it much simpler.
<snip>
The question to the group is on the atoi function.
I am converting the integer to string and so that
-> i can parse the string,
-> convert it back to integer and
-> sum it up.
( For e.g. in the above code i have sub_sum as 14)
There really is not need. You can sum the digits of a number without
converting to characters and back:
int sum_digits(int num)
{
if (num < 0)
return sum_digits(-num);
else if (num == 0)
return 0;
else return num % 10 + sum_digits(num / 10);
}
<snip>
Can someone please explain me what i am doing wrong. atoi needs the
string and i am passing a character so i tried passing the charecter
to a tmp[] and passing that to atoi function but doesnt solve my
purpose.
atoi is just the wrong function here. If you must convert to digits
using sprintf, then you convert each digit back to a number by
subtracting '0': cnt += str[i] - '0';
--
Ben.
.
- References:
- Prev by Date: Re: malloc()/realloc() - have I got this right?
- Next by Date: Re: Determine the size of malloc
- Previous by thread: Re: Help with atoi function for a numero program.
- Next by thread: How to print an array of char backward.
- Index(es):
Relevant Pages
|