Menu
CoddyTech

Ledger: Validate Commands

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

challenge icon

Challenge

Medium

Update parser.c to accept only ADD or TAKE, one space, a lowercase ASCII name of 1 through 15 letters, one space, then one or more digits representing 0 through 1000. Reject signs, trailing bytes, extra spaces, empty fields and unknown operations. On failure do not change the output Command. Invalid lines count as rejected without changing stock. Keep preceding stage behavior and report format. 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