在用结构体建立一个单链表时分别用gets()函数和scanf()函数为节点中元素赋值,代码如下
struct book
{
double price;
char name[30];
struct book *next;
};
struct book *creatlist(int n)
{
struct book *pnew, *ptail, *head;
pnew = (struct book *)malloc(sizeof(struct book));
gets(pnew->name);
scanf("%lf", &pnew->price); //在实际运行时程序会跳过这条语句
head = ptail = pnew; //在这里添加断点调试
for(int i; i < n; i++)
{
pnew = (struct book *)malloc(sizeof(struct book));
gets(pnew->name);
scanf("%lf",&pnew->price);
ptail->next = pnew;
ptail = pnew;
ptail->next = NULL;
}
return head;
}
.......
可以看到在输入字符串后没有输入数据而程序直接跳过了scanf()语句。
但是在一般的情况下,不涉及单链表,这两个函数连用就没有影响,如下
让人迷惑额
因为前面 scanf("%lf", &pnew->price);用户输入了数据和换行符‘\n’,在读取了数据之后,输入缓存里就残留了一个‘\n’。
下次再使用gets(pnew->name); 会读取输入缓存里上次残留的‘\n’,而不是读取新输入的字符。这样就造成了严重的错误。
可以在用 读取字符前用 setbuf(stdin, NULL); 清除输入缓存。
setbuf(stdin, NULL);
gets(pnew->name);
你的for循环没有给i赋予初始值啊
应该是
for(int i=0;i<n;i++)
不初始化的话,i不一定是什麽值,如果大于n的话,循环就不执行了