Skip to content

Instantly share code, notes, and snippets.

@hikilaka
Created September 25, 2018 19:42
Show Gist options
  • Save hikilaka/64b67606525ffd59e663bfcfda4241d9 to your computer and use it in GitHub Desktop.
Save hikilaka/64b67606525ffd59e663bfcfda4241d9 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
int do_operation(int a, int b, char operator) {
switch (operator) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
default: return 0;
}
}
int main() {
char buffer[256];
size_t buffer_idx = 0;
scanf("%s", buffer);
int result = 0;
int a, b;
char operator;
char tmp[32];
int read;
do {
read = sscanf(buffer + buffer_idx, "%d%c%d", &a, &operator, &b);
if (read == 3) {
result = do_operation(a, b, operator);
printf("%d\n", result);
sprintf(tmp, "%d", a);
buffer_idx += strlen(tmp);
sprintf(tmp, "%d", b);
buffer_idx += strlen(tmp);
buffer_idx += 1;
continue;
}
read = sscanf(buffer + buffer_idx, "%c%d", &operator, &a);
if (read == 2) {
result = do_operation(result, a, operator);
printf("%d\n", result);
sprintf(tmp, "%d", a);
buffer_idx += strlen(tmp);
buffer_idx += 1;
continue;
}
} while (read > 1);
printf("Result is %d\n", result);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment