LearnFrenzy
Sign in Take a free test

C Input / Output · Input/Output Programs · Question 3

Parse comma-separated records with fgets and sscanf in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links