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

时间:2022-02-14 09:44:48

Where as the same fine on Dev-C++ (TDM-GCC 4.8.1 64-bit Release), gcc version on centos is (gcc (GCC) 4.8.2 20140120 (Red Hat 4.8.2-16)). Please tell me if there is any error in my coding logic or it is something else

如果在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;
}
}` 

1 个解决方案

#1


First of all, you can't fflush(stdin); so remove that (fflush is only defined for output streams).

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

Secondly, the stdin buffer contain the newlines that the user types after entering 'Y', 'N', or a number. You can eliminate this whitespace by changing your scanf calls to have a leading space before the %c or %d, such as:

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

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

This will solve the immediate problems I see in your code.

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

#1


First of all, you can't fflush(stdin); so remove that (fflush is only defined for output streams).

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

Secondly, the stdin buffer contain the newlines that the user types after entering 'Y', 'N', or a number. You can eliminate this whitespace by changing your scanf calls to have a leading space before the %c or %d, such as:

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

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

This will solve the immediate problems I see in your code.

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