What does atoi() really do?
does it convert alpha to integers or does it test for integers?
What does atoi() really do?
does it convert alpha to integers or does it test for integers?
int atoi(const char *s)
converts s to int
so I can't use use atoi(n) by itself on a new line
n is an array filled with characters
Code:char *s_num = "123"; int num; num = atoi(s_num); /* num will now have 123 */
what if char *s_num = "hello";
instead of char *s_num = "123";
will num have "hello" in it
Look closely, num has been declared as int, so how can it ever return "hello"??? See help on atoi(). My man page says:
Which means, if:int atoi(const char *nptr);
The atoi() function converts the character string pointed to by the nptr
parameter, up to the first character inconsistent with the format of a
decimal integer, to an integer data type.
num will have 123.Code:char *s_num = "123hello"; num = atoi(s_num);
Thanks your explanation helps a lot, beter than the book I have!!!!!!!!
atoi() will return a 0 if the string can not be converted.
That's right if i type a word i'll get 0 as the result
Is there a way out of this anormal function of atoi( )?
What do you mean?
what acctually I want to know is that will atoi convert alpha to its ascii number or it has to print 0 if it encounters characters.
No it won't. Also realise that the ASCII number of an alpha is not a single digit.
So how a compiler handles atoi() called on a string containing alpha characters is implementation dependent.C Standard, 7.20.1 Numeric conversion functions, p306
If the value of the result cannot be represented, the behavior is undefined.
A simple alternative to atoi()
This code will work if the data passed to it is in the correct format.Code:long ConvertString(char* buffer) { char *ptr; long result=0; int i=0; ptr = buffer; while(*ptr!='\0') { result = (result * 10) + (*ptr - '0'); ptr++;i++; } return result; }
BUT
Realise that this code is not crash proof, it's up to you to add
checks and tests to ensure proper functionality.