c - 使用strtok将一个简单的方程存储到一个数组中,然后进行运算?

标签 c

我正在尝试使用 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/

相关文章:

python - 与 c 扩展交互时,IPython 的行为与 CPython 不同

c - 匹配字符串中的子字符串,容差为 1 个字符不匹配

c++ - 复制 C 对象

c++ - 将图像转换为 C 中可用的字节数组?

c - 如何将 char[] 中的 IP 地址转换为 c 中的 Uint32_t?

用另一根绳子剪掉一根绳子的一部分

c - 从整数中获取每个单独的数字

c - 单元测试和实现之间的重复代码

c - C中这些形式参数的含义

c - 使用无符号整数时循环条件停止在 0?