i was wondering id neone could educate me as to how to use the strtol function.. I need it to to convert a string to an integer and tell me if the string contains a non digit.. an example would make it much easier for me to undertstand.
cheers
i was wondering id neone could educate me as to how to use the strtol function.. I need it to to convert a string to an integer and tell me if the string contains a non digit.. an example would make it much easier for me to undertstand.
cheers
ssharishCode:#include <stdio.h> #include <stdlib.h> int main() { char str[] = "1236 1110011 6a66a"; char *pstr; int num1, num2, num3; num1 = strtol(str, &pstr, 10); num2 = strtol(pstr, &pstr, 2); num3 = strtol(pstr, &pstr, 16); printf("Base 10 - %d\n", num1); printf("Base 2 - %d\n", num2); printf("Base 16 - %d\n", num3); getchar(); return 0; } /* my output Base 10 - 1236 Base 2 - 115 Base 16 - 435818 */
so wat part of this function can i use to tell me if the user didnt just enter an integer??
Compare the start pointer with the end pointer, and if they're the same then the first char wasn't an integer char ('0' to '9').
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
i take it pstr is the end pointer but which is the start pointer?? and wat if the first character was a digit but the second one wasnt?
Last edited by kiz; 10-21-2007 at 02:22 AM.
say i enterd 12312 as input... wat does the end pointer get to set to?? wat can i compare it to to validate the input as an integer
if ( str == pstr )
Means the first character of str was not 0 to 9
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
yeh but wat if i entered 123a1231 as input?? how would i be able to tell then?
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
The result would be 123 and the end pointer would be pointing at the 'a'.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.