Reputation: 23
I am a beginner in C programming. I am currently preparing for an exam and I'm stuck on a program. The task is to read from a text file and make the sum of the integers inside it. The file also contains characters. I have tried this as a solution, and it is nearly correct, but it sometimes adds an integer too many times.
void calculate(char* file_name) {
FILE* file;
int sum = 0;
int number;
file = fopen(file_name, "r");
char c;
while ((c = fgetc(file)) != EOF) {
if (fscanf(file, "%d", &number)) {
printf("The number is %i\n ", number);
sum = suma + number;
}
}
fclose(file);
printf("The sum is %i\n", sum);
}
For example, the text in the file is:
asdd12 ddd15 dddgh51hh3
3adb jk !!!*
The sum should be 84 for this file, but it prints 87. Is my method completely wrong or should I just change something in the code?
Thank you in advance for your help.
Upvotes: 2
Views: 263
Reputation: 153517
... should I just change something in the code?
while((c=fgetc(file))!=EOF)
does nothing with c
and so loses a potential character of numeric input.
if( fscanf(file, "%d", &number))
is a problem as is gets fooled when end-of-file occurs as fscanf()
returned non-zero and so code thinks a number was read.
Instead try a 3-way branch. Use the result value from fscanf()
to guide the next steps.
int conversion_count;
do {
conversion_count = fscanf(file, "%d", &number);
if (conversion_count == 1) {
// scanf() found an `int`
printf("The number is %i\n ", number);
sum = sum + number;
} else if (conversion_count == 0) {
// scanf() failed to finf an `int`.
// Offending non-numeric input remains in `file`.
// Read non-numeric input character and quietly toss it.
fgetc(file); //
}
} while (conversion_count != EOF);
Alternative: Robust code would read a line of text with fgets()
and strtol()
to look for integers.
Upvotes: 2