Aprenda C · lição 46 de 60 · cerca de 10 minutos
Projeto final: Lógica principal
Escreva as funções da fatura e um laço de comandos que leia os comandos add, total e cat.
O que você vai aprender
- Escrever funções que recebem a fatura por ponteiro
- Interpretar comandos com sscanf
- Manter main pequeno
As tarefas da fatura
Agora a fatura ganha funções que a recebem por ponteiro. add_cost(&bill, what, category, pence) recusa uma fatura cheia ou um valor que não seja maior que 0 e devolve false; caso contrário, copia o texto com segurança com snprintf e devolve true. total_for(&bill, "compute") soma uma categoria, e total_for(&bill, NULL) soma tudo. Main lê comandos até end: add web2 compute 900, cat compute, total, e qualquer outra coisa recebe uma lista dos comandos.
Uma função para cada tarefa
add_expenseverifica se há espaço e depois guarda o gastototalsoma todos os valorestotal_forsoma só uma categoria- main lê linhas como
add Lunch food 650,totaloucat food
O núcleo
#include <stdio.h>
#include <string.h>
typedef struct {
char what[24];
char category[12];
int pence;
} Expense;
typedef struct {
Expense items[50];
int count;
} Tracker;
int add_expense(Tracker *t, const char *what, const char *category, int pence) {
if (t->count == 50 || pence <= 0) return 0;
Expense *e = &t->items[t->count++];
snprintf(e->what, sizeof e->what, "%s", what);
snprintf(e->category, sizeof e->category, "%s", category);
e->pence = pence;
return 1;
}
int total_for(const Tracker *t, const char *category) {
int sum = 0;
for (int i = 0; i < t->count; i++) {
if (category == NULL || strcmp(t->items[i].category, category) == 0) sum += t->items[i].pence;
}
return sum;
}
int main(void) {
Tracker t = {.count = 0};
char line[80], what[24], category[12];
int pence;
while (fgets(line, sizeof line, stdin)) {
if (sscanf(line, "add %23s %11s %d", what, category, &pence) == 3) {
printf(add_expense(&t, what, category, pence) ? "added\n" : "rejected\n");
} else if (sscanf(line, "cat %11s", category) == 1) {
printf("%s: %d\n", category, total_for(&t, category));
} else if (strncmp(line, "total", 5) == 0) {
printf("total: %d\n", total_for(&t, NULL));
}
}
return 0;
}Saída
added
added
added
rejected
food: 770
total: 975Dica
Passar NULL como categoria para significar "everything" (tudo) permite que uma única função faça as duas tarefas. Documente esse tipo de escolha em um comentário.
Ponteiros para a fatura
add_cost recebe Bill *b porque precisa mudar a fatura de verdade, não uma cópia. total_for só lê, então recebe const Bill *b, e o compilador a impede de mudar qualquer coisa sem querer. Passar um ponteiro também evita copiar a struct inteira, com os 8 custos, a cada chamada de função.
Uma cópia não muda nada
#include <stdio.h>
typedef struct {
int count;
} Bill;
void add_copy(Bill b) {
b.count++;
}
void add_real(Bill *b) {
b->count++;
}
int main(void) {
Bill bill = {.count = 0};
add_copy(bill);
add_real(&bill);
printf("%d\n", bill.count);
return 0;
}Saída
1Agora é a sua vez
Esta lição é grátis no Codiqo, com 9 perguntas sobre o que você acabou de ler. Só se aprende a programar programando, então ela termina com um pequeno programa que você mesmo escreve, e nós executamos e conferimos na hora.