【问题标题】:Why this code of ordered insertion of linked list is not working in GCC CEntos?为什么这个有序插入链表的代码在 GCC CEntos 中不起作用?
【发布时间】:2015-05-06 15:15:57
【问题描述】:

在 Dev-C++(TDM-GCC 4.8.1 64-bit Release)上同样罚款,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;
}
}` 

【问题讨论】:

  • 好的,现在解释你的问题。怎么了?是不是编译失败?是不是跑不起来了?你提供什么输入?哪里坏了?
  • 这是第一次接受我的输入,之后它没有,并且程序在发布多行后停止工作,这里是:你想输入数据吗? Y/Ny Enter your data: 5 您想输入更多数据吗? Y/N5 {此处自动输入 5}

标签: c linux gcc compiler-errors linked-list


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 2012-02-22
    • 2023-03-03
    • 2017-10-02
    相关资源
    最近更新 更多