Menu
Coddy logo textTech

Learn Skill

Lesson 5 of 8 in Coddy's User Class - OOP Project course.

challenge icon

Challenge

Easy

In this user class, you also save the skills that the user learned and their level in every skill (just like in Coddy!).

Add a method named learn that gets a skill (a string) and advances the user's level in this skill by one.

You will need some kind of data structure to manage all the skills and the levels of the user (array, list, map, etc...).

Try it yourself

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "user.h"

int main() {
    User u;
    User_init(&u, "", "");
    char line[1024];
    while (fgets(line, sizeof(line), stdin)) {
        line[strcspn(line, "\r\n")] = '\0';
        char* cmd = strtok(line, " \t");
        if (!cmd) continue;
        if (strcmp(cmd, "new") == 0) {
            char* un = strtok(NULL, " \t");
            char* em = strtok(NULL, " \t");
            User_init(&u, un ? un : "", em ? em : "");
        }
        if (strcmp(cmd, "username") == 0) { printf("%s\n", u.username); }
        if (strcmp(cmd, "email") == 0) { printf("%s\n", u.email); }
        if (strcmp(cmd, "setLocation") == 0) { char* v = strtok(NULL, " \t"); if (v) User_setLocation(&u, v); }
        if (strcmp(cmd, "getLocation") == 0) { printf("%s\n", User_getLocation(&u)); }
        if (strcmp(cmd, "info") == 0) { User_info(&u); }
        if (strcmp(cmd, "learn") == 0) { char* v = strtok(NULL, " \t"); if (v) User_learn(&u, v); }
        if (strcmp(cmd, "dumpSkills") == 0) {
            int idx[USER_MAX_SKILLS]; int n = u.skillCount;
            for (int i = 0; i < n; i++) idx[i] = i;
            for (int i = 0; i < n - 1; i++) {
                for (int j = 0; j < n - 1 - i; j++) {
                    if (strcmp(u.skills[idx[j]].name, u.skills[idx[j+1]].name) > 0) {
                        int t = idx[j]; idx[j] = idx[j+1]; idx[j+1] = t;
                    }
                }
            }
            for (int i = 0; i < n; i++) {
                printf("%s: %d\n", u.skills[idx[i]].name, u.skills[idx[i]].level);
            }
        }
    }
    return 0;
}

All lessons in User Class - OOP Project