원장: 재고 추가
Coddy의 Python 개발자를 위한 C 코스 레슨. 48개 중 43번째.
상태, 파서, 보고서 모듈을 분리해 한정된 재고 원장을 만들어 보세요. 먼저 추가 항목을 합산한 다음, 출고를 지원하고 잘못된 명령을 거부하며 정렬된 감사 보고서를 생성하세요. 공유 헤더는 처음부터 전체 인터페이스를 선언합니다. 각 다음 단계는 이전 단계의 해결 결과에서 시작하며, 잠긴 main은 변경되지 않습니다.
챌린지
중급ADD name quantity에 대해 ledger_init과 ledger_apply를 구현하세요. 수량은 0부터 1000까지이며, 반복해서 추가하면 누적됩니다. 0을 추가해도 항목이 생성됩니다. 1단계에서는 distinctNames:totalUnits 형식으로 보고합니다. 파서와 보고 함수는 제공되므로 저장된 항목의 순서를 바꾸지 마세요. 명령이 없으면 0:0을 출력합니다. 첫 번째 줄은 각 테스트에 표시된 단계 번호입니다. 그 뒤의 줄은 명령입니다. 네 단계 모두에서 같은 파일과 공개 헤더를 유지하세요. 잠긴 드라이버는 모든 단계에서 동일하며 독립된 원장을 직접 테스트합니다. 서로 다른 이름은 최대 16개이고, 각 이름은 길이가 1~15인 소문자 ASCII 문자입니다. 명령 줄은 최대 64개이며 각각 128바이트보다 짧습니다. 누적 합계는 모두 int 범위에 들어갑니다.
잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 이를 직접 호출하는 공개된 잠금 상태의 main.c와 선언된 공개 API의 호환성을 유지하세요. 또 다른 main을 추가하지 마세요. 작업에서 범위를 명시적으로 검사하지 않는 한, 모든 숫자 작업 테스트 데이터는 오버플로를 방지할 만큼 작은 값입니다. 지정된 출력만 출력하세요. 입력 파싱과 출력이 제시된 경우 드라이버가 이를 처리합니다.
직접 해보기
#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;
}
Python 개발자를 위한 C의 모든 레슨
직접 연습해 보세요: 온라인 C 컴파일러