首页 > 解决方案 > 在我的控制台计算器(C)中,scanf 在我输入变量值的树函数中工作不正确

问题描述

我正在用 C 编写一个控制台计算器,并面临以下问题。我使用树来保存和输入变量的值。我需要输入一个单独变量的值,但是在使用scanf函数时,下一个输入元素的值被输入到这个变量中。(对不起,我的英语不是母语) 例如:a+2 将输出 2。

/* structure for tree */
typedef struct tree_of_variables 
{
    char name[7];
    double value;
    struct tree_of_variables* left;
    struct tree_of_variables* right;
} tree; 

/* function to save and input variables using tree */
double tree_check(tree** t, char* c) 
{
    int j = 0;
    double b;
    if (*t == NULL)
    {
        tree* t_helper = (tree*)malloc(sizeof(tree));
        memcpy(t_helper->name, c, 7);
        t_helper->left = NULL;
        t_helper->right = NULL;
        printf("Input value ");
        while (c[j] >= 'a' && c[j] <= 'z' && j != 7)
            printf("%c", c[j++]);
        printf(":\n");
        scanf("%lf", &b);
        t_helper->value = b;
        *t = t_helper;
        return (*t)->value; 
    }

/* part of code from main */

/* char c, int i, char perem[7], tree *tr = NULL, double d) */
if (c >= 'a' && c <= 'z')
{
    i = 0;
    while (c >= 'a' && c <= 'z')
    {
        perem[i] = c;
        i++;
        if (i > 6)
        {
            printf("ERROR! Invalid variable\n");
            exit(1);
        }
        c = getchar();
    }
perem[i] = '\0';
d = tree_check(&tr, perem);
printf("Variable: %lf", d) /* output 0 */
}

标签: cvariablestreecalculator

解决方案


推荐阅读