Menu
CoddyTech

Ledger: Sorted Audit Output

Lesson 46 of 48 in Coddy's C for Java Developers course.

challenge icon

Challenge

Medium

Keep all prior parsing and stock rules. For stage 4, sort a copy of the items by name and format name=quantity entries joined by commas, then |accepted:rejected. Retain zero balances; use empty when there are no items. Do not mutate the ledger or print the previous summary. Stages 1 through 3 still use their earlier reports. The supplied buffer capacity is 1024, enough for all valid output. First line is the stage number shown in each test. Later lines are commands. Keep the same files and public header through all four steps. The locked driver is identical in every step and tests independent ledgers directly. There are at most 16 distinct names, each 1 to 15 lowercase ASCII letters, and at most 64 command lines shorter than 128 bytes. All accumulated totals fit int.

Edit the unlocked source and header files. Keep the declared public API compatible with the visible locked main.c, which calls it directly. Do not add another main. All numeric task fixtures are small enough to avoid overflow unless the task explicitly checks a range. Print only the specified output; the driver supplies input parsing and output when shown.

Try it yourself

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){
 Ledger probe,other;ledger_init(&probe);ledger_init(&other);Command sample={"ADD","probe",2};
 if(!ledger_apply(&probe,&sample) || probe.count!=1 || probe.items[0].quantity!=2 || other.count!=0)return 3;
 int stage;if(scanf("%d",&stage)!=1 || stage<1 || stage>4)return 1;
 int ch;while((ch=getchar())!='\n' && ch!=EOF){}
 Ledger ledger;ledger_init(&ledger);int accepted=0,rejected=0;char line[128];
 while(fgets(line,sizeof line,stdin)){line[strcspn(line,"\n")]=0;Command command;
  if(parse_command(line,&command) && ledger_apply(&ledger,&command))accepted++;else rejected++;
 }
 char output[1024];Ledger before=ledger;
 if(!ledger_report(&ledger,stage,accepted,rejected,output,sizeof output))return 2;
 if(ledger.count!=before.count)return 3;
 for(size_t i=0;i<ledger.count;i++)if(strcmp(ledger.items[i].name,before.items[i].name)!=0 || ledger.items[i].quantity!=before.items[i].quantity)return 3;
 puts(output);return 0;
}

All lessons in C for Java Developers

Practice on your own: Online C compiler