levijoraan levijoraan - 1 month ago 5
C Question

Trying to sum values from a text file, receiving unrecognized character as output?

Using C, I am trying sum up the numbers in a file. The file contains numbers such as:

123
456
788
...
356


When running the code, it properly asks for input and prints the number I enter. However, it does not sum the file, and just displays an unrecognized character symbol, like a small ?. I don't think the number is over the alloted INT_MAX_SIZE. What seems to be the issue?

#include <stdio.h>

main() {

//Number variable to assign each line to
int c;
int fds[2];
int childid;
int size;
int number;
int sum;

printf ("Enter the number of processes to create: ");
scanf ("%d", &number);
printf ("You entered: %d", number);
printf("\n");

//File I/O operations
FILE *file;

//Open file for reading
file = fopen("Project1_OS/project1_data/file1.dat", "r");

//If file is found
if (file) {
//While file has data to be read
while ((c = getc(file)) != EOF)
//Print data
//putchar(c);
sum+=c;


//Close the file I/O
fclose(file);
}
putchar(sum);

}

Answer

first getc it's a function for reading characters from a file not integers . you have to use fscanf :

fscanf(file,"%3d",&c)

second putchar it's a function for printing characters not intgers . so you have to write :

printf("%d",sum);