c语言缓存区

背景:创建一颗二叉树,用提示语句提示输入数据
问题:输入一个字符数据后,会连续出现两个提示语句。
进入debug后,发现在进入循环时候,第二个scanf 无法使用,
c直接有个默认值 '\n’
代码如下:

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
char data;
struct node *lchild,*rchild;

}BSTree;

void Initiate(BSTree**bt)
{
*bt=NULL;
}

void CreatBinTree(BSTree**T)
{
char n;
printf(“input data\n”);
scanf("%c",&n);
if(n==‘0’)
*T=NULL;
else
{
T=(BSTree)malloc(sizeof(BSTree));
(*T)->data=n;
CreatBinTree(&(*T)->lchild);
CreatBinTree(&(*T)->rchild);
}

}
int main()
{
BSTree *t;
CreatBinTree(&t);

return 0;

}
解决方案:
scanf 要背这个锅
函数scanf( )从标准输入设备(键盘) 读取输入的信息,不会直接赋值给变量,而是先储存到一个缓冲区中;执行到函数scanf()时,程序会从缓冲区中读取;如果缓冲区是空的,才会停滞,光标闪烁,等待键盘的输入.

另外:
-对于参数%d:会忽略缓冲区开头的空白符(空格、回车、制表符等)(无论有几个);
-对于参数 %c:直接读取缓冲区的第一个字符(无论这个字符是什么)

猜你喜欢

转载自blog.csdn.net/cruel2436/article/details/83660281
今日推荐