基本上我试图从用户那里得到一个字符串:3 + 2,作为单个字符串,单独检查字符串的组成部分并进行计算。我已经让计算器程序使用命令行输入,但如果他们不使用命令行,我需要从用户获取和读取字符串输入
这是我到目前为止所拥有的。请hellppp :(
#include <stdio.h>
#include <math.h>
int main(int argc, char *argv[]) {
int num1, num2;
float ans;
char operator;
int i = 0, j = 0;
char s[100] = " ";
char s1[100], s2[100];
if (argc==4) {
sscanf(argv[1], "%d", &num1);
sscanf(argv[2], "%c", &operator);
sscanf(argv[3], "%d", &num2);
switch (operator) {
case '+': ans = num1+num2;
printf("%d %c %d = %.2f\n", num1, operator, num2, ans);
break;
case '-': ans = num1-num2;
printf("%d %c %d = %.2f\n", num1, operator, num2, ans);
break;
case 'x':
case 'X': ans = num1*num2;
printf("%d %c %d = %.2f\n", num1, operator, num2, ans);
break;
case '^': ans = pow(num1, num2);
printf("%d %c %d = %.2f\n", num1, operator, num2, ans);
break;
case '/': if (num2 == 0) {
printf("Error! Division by Zero!\n");
}
else {
ans = num1/num2;
printf("%d %c %d = %.2f\n", num1, operator, num2, ans);
}
break;
default: printf("%c is not a valid operator!\n", operator);
}}
else
if (argc==3) {
sscanf(argv[1], "%c", &operator);
sscanf(argv[2], "%d", &num1);
switch (operator) {
case 'n':
case 'N': ans = -num1;
printf("-(%d) = %.2f\n", num1, ans);
break;
case 'a':
case 'A': ans = fabs(num1);
printf("|%d| = %.2f\n", num1, ans);
break;
case 's':
case 'S': if (num1 < 0) {
printf("Can't find square root of negative number\n");
}
else {
ans = sqrt(num1);
printf("Sqrt(%d) = %.2f\n", num1, ans);
}
break;
default: printf("%c is not a valid operator!\n", operator);
} }
else if ((argc!=3) || (argc!=4)) {
printf("Enter the string you want to calculate: ");
gets(s);
while (s[i] != '\0') {
s[i] = argv[1];
i++;
}
while
(s[i] != '\0') {
s[i] = argv[2];
i++;
}
while
(s[i] != '\0') {
s[i] = argv[3];
i++;
}}
}
else
printf("Input Error!!!\n");
}
答案 0 :(得分:2)
首先,您应该使用fgets
来读取输入,因为gets
容易受到缓冲区溢出的影响:
fgets(s, sizeof(s), stdin);
然后,您只需使用sscanf
即可获得所需的数据:
sscanf(s, "%d %c %d", &num1, &operator, &num2);