Menu
CoddyTech

Ledger: Add Inventory

Lesson 43 of 48 in Coddy's C for C++ Developers course.

challenge icon

Challenge

Medium

Implement ledger_init and ledger_apply for ADD name quantity. Quantity is 0 through 1000; repeated additions accumulate. A zero addition still creates an entry. Stage 1 reports distinctNames:totalUnits. Parser and reporter are supplied; do not reorder stored entries. Empty commands produce 0:0. 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 C++ Developers

Practice on your own: Online C compiler