0
#include<stdio.h>
void calculator();
int str_cmp(char *str1, char *str2);

int main()
{

    calculator();
}

void calculator()
{
    char str[255], operation[2];
    int num1, num2, result = 0, exit = 1, count, index;
    char op[6][3] = {{"+"}, {"-"}, {"*"}, {"/"}, {"**"}, {"%"}};

    printf("\n****CALCULATOR****\n"
           "Rules (1) You put a space each expression\n"
           "Rules (2) If you want to exit the calculator, enter '.'\n"
           "(+) Addition\n"
           "(-) Substraction\n"
           "(*) Multiplication\n"
           "(/) Division\n"
           "(**) Power\n"
           "(%%) Modulo\n");

    while (exit)
    {
        scanf("%[^\n]s", str);
        count = sscanf(str, "%s %d %d", operation, &num1, &num2);

        if (str_cmp(operation, ".") == 1)
            exit = 0;

        for (int i = 0; i < 6; i++)
            if (str_cmp(operation, op[i]) == 0)
                index = i;
        printf("index: %d", index);
    }
}

int str_cmp(char *str1, char *str2)
{
    while (*str1 && *str2 && *str1 == *str2)
        ++str1, ++str2;
    return *str1 - *str2;
}

I don't understand this section :

scanf("%[^\n]s", str); ==> infinite loop

scanf(" %[^\n]s", str); ==> not infinite loop

What is the differences "%[^\n]s" and " %[^\n]s" ?

The other parts are working. But this part confuses me.

klutt
  • 30,332
  • 17
  • 55
  • 95
bekici
  • 68
  • 10
  • 4
    Unrelated, what do you think the point of that `s` even is? It isn't part of the format specifier, so unless your input is hunting (and discarding) a hard `'s'` as input, those format strings are likely wrong for your intention regardless. Set-notation format specifiers don't need that trailing `s` specified. – WhozCraig Jan 14 '20 at 13:58
  • 1
    *Possible* duplicate: [Why is adding a leading space in a scanf format string recommended?](https://stackoverflow.com/q/26391465/10871073) ?? – Adrian Mole Jan 14 '20 at 13:58

0 Answers0