scanf () работает бесконечно, программа останавливается на операторе - PullRequest
0 голосов
/ 22 ноября 2018

Это код для BFT (ширина первого обхода) для подключенного графа.Я запускаю код, затем успешно создаю список смежности, а также успешно печатаю список смежности, но после того, как программа останавливается, когда я беру ввод от пользователя, чтобы запустить BFS с этого вводимого узла.scanf () работает бесконечно, или другая ошибка, которую я не могу определить.

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

typedef struct root               //the adjacency list which have all the vertices
{
    int info;
    struct adjacent *adj;
    struct root *next;
} root;
typedef struct adjacent             //Linked list which store adjacent nodes of any nodes in adj list.
{
    int info;
    struct adjacent *adj;
} adjacent;

typedef struct node                    // to make queue to store nodes to be explored.
{
    int info;
    struct node *next;
} nodeQ;

void insert(nodeQ **ft,nodeQ **rr,int n)      // insert func of Q
{
    nodeQ * new=(nodeQ *)malloc(sizeof(nodeQ));
    new->info = n;
    new->next = NULL;
    if(*ft == NULL)
    {   
        *ft=new;
        *rr=new;
    }
    else
    {
        (*rr)->next = new;
        *rr = new;
    }
}
int delete(nodeQ **ft,nodeQ **rr)           //delete func of Q
{
    int value=(*ft)->info;
    nodeQ *temp=*ft;
    *ft=(*ft)->next;
    free(temp);
    if(*ft==NULL)
        *rr=NULL;
    return value;
}

void BFS(int total_nodes,int node_tobe_explored,root *head,nodeQ **ft,nodeQ **rr)
{
    printf("ff");
    int * visited=(int *)malloc(sizeof(int)*total_nodes);
    for(int i=0;i<total_nodes;i++)
        visited[i]=0;                                 //initialize all value in visited array with 0
    printf("aa");
    visited[node_tobe_explored] = 1;
    printf("%d",node_tobe_explored);
    while(1)                               // this loop iterates until all nodes are not explored.
    {
        root *t=head;
        while(t->info != node_tobe_explored)    // this find the node address(t) of the node_tobe_explored.
            t=t->next;
    printf("bb");
        adjacent * adj_node = t->adj;

        while(adj_node)
        {
            if(visited[adj_node->info] == 0)    //if that adjacent node is not visited then also we visit it.
            {
                int adj_node_val = adj_node->info;
                visited[adj_node_val] = 1;
                insert(ft,rr,adj_node_val);
                printf(", %d",adj_node_val);
            }
        }
            printf("cc");
        if(*rr==NULL)        //if Q is empty, means all nodes are explored, so we return.
            return;
        else                   //otherwise explore first node present in Q
            node_tobe_explored = delete(ft,rr);
    }
}

int main()
{ 
    char ch;
    int no,tot_nodes,start;
    nodeQ *front=NULL,*rear=NULL;
    printf("enter the no. of nodes: ");
    scanf("%d",&tot_nodes);
    root *head = NULL;
    no = tot_nodes;
    while(no!=0)
    {                                              //to make the main chain of adjacency list.
        root *new=(root *)malloc(sizeof(root));      
        new->info = no;
        new->adj = NULL;
        new->next = head;
        head = new;
        no--;
    }
    root *temp = head;
    while(temp!=NULL)
    {                                                  // to add the adjacent nodes to main chain.

        printf("enter the nodes adjacent to %d:\n",temp->info);
        do
        {
            int element;
            printf("  enter node: ");
            scanf("%d",&element);
            adjacent *nw = (adjacent *)malloc(sizeof(adjacent));
            nw->info = element;
            nw->adj = temp->adj;
            temp->adj = nw;

            printf("more adjacent nodes y/n: ");
            ch=getchar();
            ch=getchar();
        }while(ch=='Y'||ch=='y');

        temp=temp->next;
    }
    printf("display of the structur of the linked list formed:\n");
    root * head1=head;
    while(head1)                               // to display the formed adj. list.
    {
        printf("%d--",head1->info);
        adjacent *t = head1->adj;
        while(t)
        {   
            printf("%d,",t->info);
            t=t->adj;
        }
        printf("\n");
        head1=head1->next;
    }

    do
    {
        printf("enter the node value from which you want to start BFS: ");
            printf("before [enter image description here][1]");
            int st;
        scanf("%d",&st);
            printf("after");
        BFS(tot_nodes,st,head,&front,&rear);             //calling BFS func.
        printf("do you want to print more traversals y/n: ");
        ch=getchar();
        ch=getchar();
    }while(ch=='Y'||ch=='y');
}

1 Ответ

0 голосов
/ 22 ноября 2018

Выдержка из исходного кода OP:

    printf("do you want to print more traversals y/n: ");
    ch=getchar();
    ch=getchar();
}while(ch=='Y'||ch=='y');

Вероятно, намеревалось прочитать письмо ( y или n ) и \n, которые подтвердиливход.

Итак, 2 nd ch=getchar(); (для ENTER ) переопределяет ранее прочитанное письмо.Следующее исправление изменит это:

    printf("do you want to print more traversals y/n: ");
    ch=getchar();
    getchar(); /* ignore the returned value - it's just to consume '\n'. */
}while(ch=='Y'||ch=='y');

Кстати.это то, что должно было быть обнаружено путем пошаговой отладки приведенных четырех строк ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...