I’m currently working through Project Euler problems as a way of learning C and I’m having trouble with problem #8, the actual maths and main bit of program is fine but the method requires reading individual digits from a large (1000 digit) number, which I put in a file.
The code below is for a test case, where my file “test.txt” is the number “123456789”. What I am trying to do is print out each digit on a separate line.
#include <stdio.h>
int main()
{
int c = 0;
FILE *fp;
fp = fopen("test.txt", "r");
while(c != EOF)
{
c = fgetc(fp);
printf("%i\n", c);
}
fclose(fp);
}
When I run this code, I get the output
49
50
51
52
53
54
55
56
57
10
-1
I have a hunch I am missing something really simple from my code and I would expect it is in the fgetc bit. If this is the case, what would be a better function to use and I’m also curious of why I get such a weird output – when I try it with my 1000 digit number I find a similar pattern with numbers around 49 to high 50s being output almost cyclically. Please bear in mind I am only a beginner with C, cheers.
Those are ASCII for the digits:
etc. They’re in that format because they’re characters stored in a text file which represent integer digits.
You need to print:
Note: You’ll want that
ifcheck because the 10 is a newline and the -1 is EOF, you’re printing more then you wanted.Of course there are lots of ways to do this if check:
or
The point is simply that you need to check if you only want digits.