1
基本上我試圖從用戶處獲得一個字符串,格式爲:3 + 2,作爲單個字符串,單獨檢查字符串的組成部分並進行計算。我已經有計算器程序使用命令行輸入,但我需要從用戶那裏讀取字符串輸入,如果他們不使用命令行C中計算器的讀取字符串輸入
這是我到目前爲止。請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");
}
首先,你應該使用['fgets'(http://en.cppreference.com/w/c/io/fgets)以獲取輸入的來自用戶的線路其次,整個字符串是以''\ 0''結尾,而不是字符串中的每個「單詞」。第三,查看['strtok'](http://en.cppreference.com/w/c/string/byte/strtok)函數來分隔分隔符上的字符串。第四點,你嘗試給一個字符('s [i]')分配一個字符串(例如'argv [1]')。最後,您可以直接在您讀取的字符串上使用'sscanf',無需分割它。 – 2013-03-15 12:00:39
'但我需要從用戶那裏讀取字符串輸入,如果他們不使用命令行 - - 那麼這是什麼特別是你的問題? – Mike 2013-03-15 12:01:56
使用適當的字符串函數並使其與計算器一起工作 – user2173788 2013-03-15 12:05:45