The following questions assume the file test contains comma-delimited digits on
ID: 3644672 • Letter: T
Question
The following questions assume the file test contains comma-delimited digits on separatelines as follows:
4,7,1,2,7
1,8,3
1,2,8,3,4,7,9,4,1,0
Thus each line contains a list of single digits separated by comma.
Write a program called p1 that calculate the sum of the digits in the CSV format (given
above) from standard input. Your program should return the sum onto the standard output.
You must use C programming language and the corresponding source code must be in the file
p1.c.
For example:
$p1 < test
72
Explanation / Answer
#include #include int main() { FILE *fp; fp=fopen("test.txt","r"); if(fp==NULL) { printf("i cant open the file. "); exit(1); } else { printf("i got the file. "); int i,j; char ch; int sum=0; do { fscanf(fp,"%d" ,&i); ch=fgetc(fp); sum=sum+i; if(ch==' ') { printf("sum of the line is %d. ",sum); sum=0; } }while(ch!=EOF); printf("sum of the line is %d. ",sum); } }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.