Maybe something like this:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct Objective {
char *name;
int id;
int duration;
int ndeps;
int *dep;
} Objective;
void print_objective(Objective *o) {
printf("Id : %d\n", o->id);
printf("Name: %s\n", o->name);
printf("Duration: %d\n", o->duration);
if (o->ndeps == 0)
printf("no deps\n");
else {
printf("deps: ");
for (int i = 0; i < o->ndeps; i++)
printf("%d ", o->dep[i]);
printf("\n");
}
}
char *readline(FILE *fin) {
char buf[1000];
char *line = NULL;
size_t size = 0;
while (fgets(buf, sizeof buf, fin) != NULL) {
size_t len = strlen(buf);
line = realloc(line, size + len + 1);
strcpy(line + size, buf);
size += len;
if (line[size - 1] == '\n') {
line[size - 1] = '\0';
break;
}
}
return line;
}
bool do_add_command(const char *line, Objective *o) {
char name[8001];
int dep[9001];
int n;
if (sscanf(line, "%d%n", &o->id, &n) != 1) {
printf("No id\n");
return false;
}
char ch = '\0';
sscanf(line += n, " %c%n", &ch, &n);
if (ch != '"') {
printf("No starting quote\n");
return false;
}
*name = '\0';
if (sscanf(line += n, "%8000[^\"]%n", name, &n) != 1 || !*name) {
printf("No name\n");
return false;
}
int sz = strlen(name);
o->name = malloc(sz + 1);
strcpy(o->name, name);
ch = '\0';
sscanf(line += n, " %c%n", &ch, &n);
if (ch != '"') {
printf("No ending quote\n");
return false;
}
if (sscanf(line += n, "%d%n", &o->duration, &n) != 1) {
printf("No duration\n");
return false;
}
o->ndeps = 0;
while (sscanf(line += n, "%d%n", &dep[o->ndeps], &n) == 1)
o->ndeps++;
if (o->ndeps > 0) {
size_t sz = o->ndeps * sizeof *o->dep;
o->dep = malloc(sz);
memcpy(o->dep, dep, sz);
}
return true;
}
int main() {
char *line;
while ((line = readline(stdin)) != NULL) {
char command[50];
int n = 0;
sscanf(line, "%49s%n", command, &n);
if (strcmp(command, "add") == 0) {
Objective o;
if (do_add_command(line + n, &o))
print_objective(&o);
}
else if (strcmp(command, "remove") == 0) {
}
else if (strcmp(command, "quit") == 0) {
break;
}
else {
printf("Unrecognized command\n");
}
free(line);
}
return 0;
}