我正在尝试使用 strtok
分解一个简单的等式,例如 5 + 4
并将每个部分存储到一个数组中,完成后,执行操作指示。
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
//#include "stdafx.h"
int main() {
char uin[10], op[10], error = 'e';
char *token;
const char s[2] = " ";
double num1, num2, fNum1, res;
int i = 0;
int x, y, z, a, b, c, op1;
printf("Welcome to the calculator, please enter an equation\n");
while (error == 'e') { // & assigns address and * gives access to what it points to
a = &uin[0];
b = &uin[2];
c = &uin[4];
gets(uin);
rewind(stdin);
printf("Is this what you entered? %s\n", uin);
token = strtok(uin, s);
//x = &token;
//printf("The element in the array currently assigned to token is: %s\n", token);
while (token != NULL) {
if (isdigit(token[0])) {
num1 = atof(token);
printf("token is now: %1.2f\n", num1);
} else
strcpy(op, token);
token = strtok(NULL, s);
if (isdigit(token[0])) {
num1 = atof(token);
} else
strcpy(op, token);
//token = strtok(NULL, s);
//y = &token;
//printf("The element in the array currently assigned to token is: %s\n", token);
}
//token = strtok(NULL, s);
//y = &token;
//printf("The element in the array currently assigned to token is: %s\n", token);
//token = strtok(NULL, s);
//z = &token;
//printf("The element in the array currently assigned to token is: %s\n", token);
}
system("pause");
}
我真的很难过。我认为我正在使用 strtok
正确地获取 gets(uin)
的第一部分并存储它,但我不明白如何获取中间部分( +
-
*
或 /
) 并存储。
最佳答案
strtok
不是适合您的目的的工具。 strtok
修改字符串,覆盖分隔符。它只适用于所有标记都由空格分隔的表达式,这是一种不必要且违反直觉的约束。要获得更有效的方法,请对每个字符使用指针和显式测试,或使用非侵入式解析助手,例如 strspn()
、strcspn()
和 strtold ()
。
此外,你不应该使用 gets()
,这个函数已经过时并且从最新版本的 C 标准中删除了。它不能安全地使用:任何足够大的输入都会破坏您的程序并产生未定义的行为。使用 fgets()
而不是将整行读入足够大的数组:10 个字节肯定太小了。 rewind()
也是不必要的。
关于c - 使用strtok将一个简单的方程存储到一个数组中,然后进行运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54610562/