Home > database >  How to remove 2 strings from one building another in C
How to remove 2 strings from one building another in C

Time:12-28

I couldn't really word the title correctly so please read this question fully.

I am trying to make a custom language, which is working out pretty nicely.

I want to create an Input command that logically saves the variable to memory for later calling, this has worked and the below example works without any problems, the thing is that printing tree->parts[3].value results in anything being printed until it hits a whitespace, but if you want the code to ask the user this: Your Input: it cuts the rest off. The variable string has everything and not just a part of it, which means that by stripping tree->parts[1].value and tree->parts[2].value from it, leads to the complete string that can be printed.

I am kind of lost on this part and don't know where to start, as I usually do this with C and RegEX or some C function.
I could port my code to C and do it there, but how could I achieve this with C?

The command goes as follows: input [Variables Name] = [String to print before asking input]
ex. input name = What's your name?.

Without going too deep into the code, here are a few helpful snippets providing a "reproducible example".


Creating and setting variables parseString method:

int setVariable(char *name, char *value, struct Memory *memory);

int createVariable(char *name, char *value, struct Memory *memory);

void parseString(char *buffer, struct Tree *tree, struct Memory *memory);

The tree struct:

struct Tree {
    int ignore;
    char ignoreType;

    int indent;
    struct Parts parts[10];
    int partsLength;
    struct Strings strings[10];
    int stringsLength;
};

If needed the memory struct:

struct Memory {
    struct Variables {
        char name[128];
        char value[MAX_STRING];
        int length;
    }variables[50];
    int variablesLength;
    struct Labels {
        char name[128];
        int line;
        int lastUsed;
    }labels[50];
    int labelsLength;
};

The code used for the Input:

else if (!strcmp(first, core->command[11].first)) {
    // input
    char input[100];
    printf(string);
    printf(tree->parts[3].value);
    scanf("%s", input);
    createVariable(
        tree->parts[1].value,
        input,
        memory
    );
}

CodePudding user response:

To parse "input name = What's your name?" into "input", "name" and "What's your name?", use sscanf() and "%n" to note where scanning stopped.

char var[128];
int n = 0;
sscanf(input, " input 7s = %n", var, &n);
// If success
if (n > 0) {
  printf("var %s = <%s>\n", var, input   n);
}
  • Related