Friday, July 31, 2009

Reading integers from FILE in C?

I have a file that has integers on one line diveded by one space and nothing else.


For ex:


6 23 -2 45 -11





I have to do more things with these numbers, find the sequence with the maximum sum and others. But that's not the problem, I can do that. The problem is reading these numbers as integers and not as strings. I've tried reading them as strings and then using atoi() but I get a warning about atoi: "passing arg 1 of atoi makes pointer from integer without cast" - something like that.


My declaration is char b[1000]; char c. c is the variable in which I read characters from the file with getc(). If I declare them as char *b, *c, I don't get any more warning for atoi() but reading from the file doesn't work anymore.


Any suggestions?

Reading integers from FILE in C?
Have you tried looping (until end-of-line or EOF) using fscanf? This function is used like fprintf/printf. So,


FILE *filePointer;


int myInt;





/* Open the filePointer...blah blah blah */





/* Read an integer into myInt */


fscanf(filePointer, "%d", %26amp;myInt);





No atoi conversion is needed in this case...it's already an int. The getc function will only retrieve one character at a time. For example, 23 would be read as 2 and then 3. Alternatively, you could read like this, entering each character into a char array until you hit a space and then, after adding a null-string char ("\0") send this into atoi.


No comments:

Post a Comment