Re: Help with atoi function for a numero program.
- From: Glenn Hutchings <zondo42@xxxxxxxxxxxxxx>
- Date: Fri, 30 May 2008 18:48:20 +0100
Ram <sriram.n83@xxxxxxxxx> writes:
char str[100],tmp[1];
<snip>
for ( i=0; str[i]!='\0'; i++)
{
tmp[0]=str[i];
c=atoi(tmp); // I need help here
cnt=cnt+c;
}
<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)
1. i am checking for the condition is true then i am converting the
integer to string using sprintf. This works fine. The string is
declared as an character array. In this program char str[100];
2. Then using for loop to check for end of line
now str[0] = 1 and later str[1] = 4
now i use atoi to convert the string to integer so that i can
perform the sum.
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.
Strings in C must be terminated by a zero ('\0') character to be usable
correctly in C library functions. Your tmp array doesn't have this. If
you define it as tmp[2], and add the line
tmp[1] = '\0';
after the tmp[0] assignment, it should work.
There are much better ways to do what you're trying to do in various places
in your program: check out the sscanf() library function. It scans the
contents of a string and places the results into one or more variables
directly.
Oh, and the // style of comments are C++, not standard C, although most
compilers these days will accept them anyway. The C style of comment is
like /* this */.
Glenn
.
- Follow-Ups:
- Re: Help with atoi function for a numero program.
- From: Ram
- Re: Help with atoi function for a numero program.
- From: santosh
- Re: Help with atoi function for a numero program.
- References:
- Prev by Date: Re: Four or Two Bytes?
- Next by Date: Re: Determine the size of malloc
- Previous by thread: Help with atoi function for a numero program.
- Next by thread: Re: Help with atoi function for a numero program.
- Index(es):
Relevant Pages
|