c - 为什么这段链表有序插入代码在 GCC CEntos 中不起作用?

标签 c linux gcc compiler-errors linked-list

在 Dev-C++(TDM-GCC 4.8.1 64 位版本)上同样适用,centos 上的 gcc 版本是 (gcc (GCC) 4.8.2 20140120 (Red Hat 4.8.2-16))。 请告诉我,如果我的编码逻辑有任何错误或其他原因

`#include<stdio.h>
    #include<stdlib.h>
struct node
{
    int i;
    struct node *next;
};
void main()
{
struct node *head,*temp,*p;
int d;
char ch;
printf("Do you want to enter data? Y/N");
scanf("%c",&ch);
fflush(stdin);
if((ch=='y')||(ch=='Y'))
{
    printf("Enter your data: ");
    scanf("%d",&d);
    fflush(stdin);
    head=(struct node *)malloc(sizeof(struct node));
    head->i=d;
    head->next=NULL;
}
p=head;
printf("Do you want to enter more data? Y/N");
scanf("%c",&ch);
fflush(stdin);
while((ch=='y')||(ch=='Y'))
{
    temp=(struct node *)malloc(sizeof(struct node));
    printf("Enter your data: ");
    scanf("%d",&d);
    fflush(stdin);
      temp->i=d;
    temp->next=NULL;
    if(p->i>=temp->i)
    {
        temp->next=head;
        head=temp;
    }
    else
    {
        while((p->next!=NULL)&&(p->next->i<temp->i))
        {
            p=p->next;
    }
        temp->next=p->next;
        p->next=temp;
    }
    printf("Do you want to enter more data? Y/N");
scanf("%c",&ch);
fflush(stdin);
p=head;
}
while(p!=NULL)
{
    printf("%d ",p->i);
    p=p->next;
}
}` 

最佳答案

首先,你不能 fflush(stdin); 所以删除它(fflush 只为输出流定义)。

其次,标准输入缓冲区包含用户在输入“Y”、“N”或数字后键入的换行符。您可以通过将 scanf 调用更改为在 %c 或 %d 之前有一个前导空格来消除此空格,例如:

scanf(" %c",&ch);
...
scanf(" %d",&d);

这将解决我在您的代码中看到的直接问题。

关于c - 为什么这段链表有序插入代码在 GCC CEntos 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30080861/

相关文章:

c++ - 如何让-1==-1.0000000000001

python subprocess.stdout.readline 没有

gcc - 我可以使用 GCC 编译器和 Clangd 语言服务器吗?

linux - 如何在 linux 中的 postscript 或 pdf 文件的每一页底部添加页脚?

Linux空间检查

c++ - DisplayImage.cpp 错误 将 OpenCV 与 gcc 和 CMake 结合使用

c++ - 使用 GCC-4.8.1 在 MinGW 上编译 wxWidgets-2.8.12 时出错

c - 为什么两个相同的指针与 -O1 比较不相等?

c - 从链接列表中删除

iphone - 在 Objective C (Cocoa) 线程中运行 C 代码(适用于 iOS)