我已经用C语言编写了一个简单的计算器应用程序,目前它运行得相当不错,但是我缺少一件事情:如何确保用户输入的格式正确,例如"6 + 7"。有没有办法进行测试?
以下是我的代码:
/*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;
}
"%d %c %d"
的sscanf
函数,并检查其返回值。如果返回值为 3,则表示成功。然后,您只需要检查运算符是否有效即可。 - Eraklon