Read lines of the form name,age,score, parse each with sscanf, report lines that do not match, and print the average score.
Solution
main.c
#include <stdio.h>
int main(void) {
char line[100], name[30];
int age, lineno = 0, count = 0;
double score, sum = 0;
while (fgets(line, sizeof line, stdin) != NULL) {
lineno++;
if (sscanf(line, "%29[^,],%d,%lf", name, &age, &score) != 3) {
printf("line %d skipped\n", lineno);
continue;
}
printf("%-5s age %d score %.1f\n", name, age, score);
sum += score;
count++;
}
if (count > 0)
printf("average %.2f\n", sum / count);
return 0;
}
Output Verified by compiling and running
Asha age 21 score 88.5
line 2 skipped
Ravi age 23 score 74.0
average 81.25
%29[^,] reads up to 29 characters that are not commas – a scanset, the way to read text containing spaces. Parsing each line separately means one bad line cannot break the rest.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!