c - 在我的控制台计算器(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 */
}
解决方案
推荐阅读
- angular - 模态中的额外内容类
- docker - Docker swarm - DNS 服务发现,寻找内部结构
- python-3.x - Python 3:对象没有属性
- python - 使用表单提交按钮 JQuery + Django 更改布尔值
- javascript - API 从城市名称中获取地区、州和国家名称
- jquery - 如何在不使用表标签的情况下将 jquery 数据表与 bootstrap jumbotron 一起使用
- javascript - 来自构造函数的 HTML 元素标记名称
- mysql - 如何查找同一组数据的日期中的空白 - mySQL
- reactjs - 如果使用jsx的地图功能中的条件如何更改bg颜色?
- ios - Alamofire swift 4中的POST请求