I've written a simple calculator app in C and it works pretty well so far but I'm missing one thing: how to ensure the user has entered an input in the correct form e.g. "6 + 7". Is there any way I can test for that?
Here is my code so far:
/*A simple calculator that can add, subtract and multiple. TODO: Division
and add error handling i.e. if not an expected input!*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char input[10];
int result;
printf("Welcome to the calculator! The available operations are +, - and *.\n");
while (1) {
printf("What would you like to calculate?\n");
fgets(input, 10, stdin); /*Getting user input in form e.g. 4 + 7*/
/*Ideally test for input should go here*/
/*Separating user input into the numbers and operators, using strtok and
space as a delimiter*/
char *firstNumber = strtok(input, " ");
char *operator = strtok(NULL, " ");
char *secondNumber = strtok(NULL, " ");
/*Converting the separated numbers to integers*/
int firstInt = atoi(firstNumber);
int secondInt = atoi(secondNumber);
if (strcmp(operator, "+") == 0) {
result = firstInt + secondInt;
} else if (strcmp(operator, "-") == 0) {
result = firstInt - secondInt;
} else if (strcmp(operator, "*") == 0) {
result = firstInt * secondInt;
} else {
printf("That ain't a valid operator sonny jim. Try again:\n");
continue;
}
printf("Your result is %d.\n", result);
int flag = 0;
while (flag == 0) {
printf("Would you like to do another calculation? (yes or no)\n");
fgets(input, 10, stdin);
if (strcmp(input, "yes\n") == 0) {
flag = 1;
} else if (strcmp(input, "no\n") == 0) {
flag = 2;
} else {
printf("That isn't a valid response. Please respond yes or no.\n");
}
}
if (flag == 2) {
break;
}
}
return 0;
}