i find a problem using atoi() method in ansi c?
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 te开发者_StackOverflow中文版mp="2" it returns me 20 instead of 2 what i have to do to get the accurate values, help required.
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.
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));
I guess, the problem is not atoi, should be something else. Please check pointers, debug step by step, etc.
精彩评论