tags:

views:

152

answers:

3

i have a string initialized by {'\0'} every time i a loop and store some chars in it ranging from 0 to 9 when i convert atoi(temp) where temp="2" it returns me 20 instead of 2 what i have to do to get the accurate values, help required.

A: 

A couple of things to check:

  • Have you re-terminated the string, after adding your character(s)?
  • Have you allocated enough memory for the whole string, including the new null terminator?

Something like this should work:

char buffer[2] = {'\0'}; // note "[2]" to set aside two bytes
buffer[0] = '2';
buffer[1] = '\0'; // ensure it's still terminated
printf("%d\n", atoi(buffer));
Andy Mortimer
You don't have enough information to answer this question; additionally with `char buffer[2] = {'\0'};` **all** `buffer[x]` (0 and 1 in this case) are guaranteed to be zero. There is no need to do `buffer[1] = '\0';` so it can't be the cause of the problem.
Andreas Bonini
You're right about the null termination on the first iteration, but since (as you say) we don't have the code, we don't know whether the OP is reusing the buffer, or how many characters he's putting in each time around. Explicitly null-terminating, although sometimes overkill, is always safe.I figured a partial answer, which may or may not help, was more use than no answer at all. I guess you disagree.
Andy Mortimer
+1  A: 

No matter what your problem with getting atoi to work is, you should rather use strtol. From the libc info manual:

-- Function: int atoi (const char *STRING)

 This function is like `atol', except that it returns an `int'.
 The `atoi' function is also considered obsolete; use `strtol'
 instead

See this answer for example of how to use strtol.

hlovdal
A: 

I guess, the problem is not atoi, should be something else. Please check pointers, debug step by step, etc.