RESULT: Segmentation faultCode:int i; char a; FILE *input = fopen( "a.c", "r" ); for(i = 0; i < 1000; i++){ if (( a = getc(input)) == '2') i = (int)atoi(a); printf("%d",i); }
I tried with a as an integer
???
RESULT: Segmentation faultCode:int i; char a; FILE *input = fopen( "a.c", "r" ); for(i = 0; i < 1000; i++){ if (( a = getc(input)) == '2') i = (int)atoi(a); printf("%d",i); }
I tried with a as an integer
???
I don't see how that could compile. atoi() works on a string, not a char.
If you turn up the warning level on your compiler, you will probably get a warning saying "converting int to char * without a cast" or some such. It's because you are passing a single char into atoi() which expects a string.
If you have a single char, you can convert it to an integer by subtracting the zero character (assuming all digits are in the correct sequence 0..9 without gaps, but this holds true for the two most common character encodings ASCII [and ASCII extensions, including UNICODE as long as we use wester-arabic-based diigts] as well as EBCDIC, so we probably cover 99.99% of all system with this).
With your code, the atoi() function tries to read memory at adress 50, which is invalid in all modern operating systems.Code:i = ch - '0';
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
I think my original suggestion is better, but if you must:
But since the conversion from character to integer is so simple, this is like walking around the entire block to get to your next door neighbours house.Code:char str[2]; ... str[0] = ch; str[1] = '\0'; atoi(str);
--
Mats
Last edited by matsp; 03-30-2009 at 01:17 PM. Reason: Add starting code tag.
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
Thank you very much.