Tom4045
Tom4045

Reputation: 29

How can I retrieve three variables from a user input in C

I need to make a small calculator for school, using the following template: "operation(operator1, operator2)". E.G.: "Add(1, 2)" will return 3, "Multiply(2, 5)" will return 10. I know I can use a strtok to retrieve the operation, but I'm not sure how to retrieve the operators. Currently I have the following:

#include <stdio.h>
int main()
    {
        char Math_Input[32]; //This is where I will store the input in the following template: operation("operator1, operator2")
        float Operator_1, Operator_2;

        printf("What calculation do you wish to do?: ");
        fgets(Math_Input,20,stdin); //Here I retrieve the entire line and I'll store it in Math_Operation, next step is to retrieve the operation, operator1 and operator2

        char * Math_Operation = strtok(Math_Input, "(");

        printf("%s\n", Math_Operation);

    }

Update:

After a bit of code given which is using sscanf() I revised my code to the following:


#include <stdio.h>
int main()
    {
        char Math_Input[32]; //This is where I will store the input in the following template: operation("operator1, operator2")
        char Math_operation[16];
        float Operator_1, Operator_2;

        printf("What calculation do you wish to do?: ");
        fgets(Math_Input,20,stdin); //Here I retrieve the entire line and I'll store it in Math_Input, next step is to retrieve the operation, operator1 and operator2
        if (3 != sscanf(Math_Input, "%15s (%f ,%f )", Math_operation, &Operator_1, &Operator_2)) {
            fprintf(stderr, "Incorrect line >%s<\n", Math_Input);
                printf("Operation: %s \n", Math_operation);
                printf("Operator1: %d \n", Operator_1);
                printf("Operator2: %d \n", Operator_2);
            }
        else {
                // Ok process the operation...
                printf("Else");
                printf("Operation: %s \n", Math_operation);
                printf("Operator1: %d \n", Operator_1);
                printf("Operator2: %d \n", Operator_2);
            }

    }

I used a few printf's to debug. This should work in theory right? But when I test it out like this: (so this is my console) it doesnt seem to work...

What calculation do you wish to do?: Add(1, 2)
Incorrect line >Add(1, 2)
<
Operation: Add(1,
Operator1: 0
Operator2: 0

Process returned 0 (0x0)   execution time : 3.698 s
Press any key to continue.

Upvotes: 1

Views: 70

Answers (3)

Shubham
Shubham

Reputation: 1153

As you said in the comments:

the user will be typing in "Add(1,2)" or "Multiply(2,5)"

you can just do what you are doing i.e. tokenizing the string:

#include <stdio.h>
#include <string.h>

int main()
{
        int data_field = 3;
        char Math_Input[32];
        char* Math_Operation = NULL;
        // operation("operand1,operand2")
        float operand_1, operand_2;

        printf("What calculation do you wish to do?: ");
        scanf("%31[^\n]%*c", Math_Input);

        Math_Operation = strtok(Math_Input, "(");
        while(data_field-- != 0)
        {
                printf("%s\n", Math_Operation);
                if (data_field == 2)
                {
                        Math_Operation = strtok(NULL, ",");
                        sscanf(Math_Operation, "%f", &operand_1);
                }
                if (data_field == 1)
                {
                        Math_Operation = strtok(NULL, ")");
                        sscanf(Math_Operation, "%f", &operand_2);
                }
        }
        return 0;
}

Output:

What calculation do you wish to do?: Add(2,1)
Add
2
1

P.S.: You can store operands using sscanf().

Upvotes: 1

Serge Ballesta
Serge Ballesta

Reputation: 149085

If the input is expect to be in the format operation(value_1, value2), it looks like a correct use case for sscanf. The scanf family is said to be a poor man's parser, because it has no support for error recovery. But here you have already got your input line from fgets and only need a trivial parsing. So I would just use:

    char Math_Input[32]; //This is where I will store the input in the following template: operation("operator1, operator2")
    char Math_operation[16];
    float Operator_1, Operator_2;

    printf("What calculation do you wish to do?: ");
    fgets(Math_Input,20,stdin); //Here I retrieve the entire line and I'll store it in Math_Operation, next step is to retrieve the operation, operator1 and operator2
    if (3 != sscanf(Math_Input, "%15[^ (] (%f ,%f )", Math_operation, &Operator_1, &Operator_2)) {
        fprintf(stderr, "Incorrect line >%s<\n", Math_input);
    }
    else {
        // Ok process the operation...
    }
    ...

The good news with sscanf is that it will ignore any non significative blank character.

Additional improvements: make sure that fgets could get a complete line (not more than 19 characters) else read until the end of line in you later need a loop

Upvotes: 1

kocotian
kocotian

Reputation: 127

In my opinion, the best (and most efficient) way would be to write a simple parser, something like this:

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

int
main(void)
{
    char input[32], function_name[32];
    float function_args[2];

    char *iterator, *bufptr, buffer[32];
    /* we will use buffer to temporarily store float,
       and bufptr to store tokens beginning */

    printf("What calculation do you wish to do?: ");
    fgets(input, 20, stdin);

    /* On this step we have input, probably in format `name(val1, val2)`.
       Now we are going to parse this: */

    iterator = input; /* iterator will point to first character of an input */
    bufptr = iterator; /* bufptr will now point to a beginning of a token */
    while (*iterator != '(' && *iterator != '\0')
        ++iterator;

    /* Now iterator points to '(', or string ended because we got
       NULL-terminator, so we will check for a terminator: */

    if (*iterator == '\0') { /* String ended */
        fputs("Syntax error :(", stderr);
        exit(1);
    }

    /* Copying function name to function_name variable.
       We will copy amount of characters equal iterator - input,
       because we added 1 to iterator, so iterator points to '(' now: */

    strncpy(function_name, bufptr, iterator - bufptr);

    /* Now, we are doing exacly the same thing, but now for ','.
       You can surround this loops with a function: */
    ++iterator; /* iterator points to '(', so we will just add 1 */
    bufptr = iterator;
    while (*iterator != ',' && *iterator != '\0') ++iterator;
    if (*iterator == '\0') { /* String ended */
        fputs("Syntax error :(", stderr);
        exit(1);
    }

    strncpy(buffer, bufptr, iterator - bufptr);
    function_args[0] = strtof(buffer, NULL);

    /* Now we can continue parsing, iterator now should point to a comma.
       Doing same thing as upper, but now for ')' */
    ++iterator;
    bufptr = iterator;
    while (*iterator != ')' && *iterator != '\0') ++iterator;
    if (*iterator == '\0') { /* String ended */
        fputs("Syntax error :(", stderr);
        exit(1);
    }

    strncpy(buffer, bufptr, iterator - bufptr);
    function_args[1] = strtof(buffer, NULL);

    while (*iterator != ')' && *iterator != '\0') ++iterator;
    if (*iterator == '\0') { /* String ended */
        fputs("Syntax error :(", stderr);
        exit(1);
    }

    /* Printing */
    printf("Function that you called: %s(%f, %f)\n",
            function_name, function_args[0], function_args[1]);

    /* And on this point you have all expected data, so you can call functions */
    if (!strcmp(function_name, "Add")) {
        Add(function_args[0], function_args[1]);
    } else if (!strcmp(function_name, "Substract")) {
        Substract(function_args[0], function_args[1]);
    } else {
        /* ... */
    }
}

Upvotes: 1

Related Questions