C, проблема двусвязного списка - PullRequest
0 голосов
/ 27 апреля 2011

Я пытаюсь прочитать ввод от пользователя о клиенте.

Ввод: Майк, 404 запрещенных ул, Роли, NC, 27607,123.78

Затем добавьте этого клиента в отсортированный по алфавиту двусвязный список. Пользователь может выбрать для вставки записи, удаления и записи, или просмотреть список. После добавления пользовательского элемента управления мой sscanf больше не работает должным образом. Я не могу понять, почему. Я не понимаю, почему я не могу печатать значения клиентов в пользовательской версии управления.

Кроме того, любые советы / ссылки относительно синтаксиса обновления предыдущего поля узлов были бы очень полезны: P

Заранее спасибо

Работает (без контроля пользователя):

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXNAMELEN 19
#define MAXADDRLEN 49
#define MAXCITYLEN 19
#define MAXSTATELEN 2

struct aNode {
    char name[MAXNAMELEN];
    char address[MAXADDRLEN];
    char city[MAXCITYLEN];
    char state[MAXSTATELEN];
    int zip;
    float balance;
    struct aNode *next;
    struct aNode *prev; 
};

typedef struct aNode node;
struct aNode *dLList;

void read();
void input();
void print();
void delete();
int insertSort(node*);

int main() {

    //from text file
    read();

    input();  
        /*
    int choice;
    while(1) {
        printf("\n1.INSERT\n2.DELETE\n3.DISPLAY\n4.END\n");
        printf("Enter choice:");
        scanf("%d",&choice);
        switch(choice) {
        case 1:
            input();
            break;
        case 2:
            delete();
            break;
        case 3:
            print();
            break;
        case 4:
            exit(0);
        }
    }
    */
    return(0);
}

//TODO
void read() {

}

void input() {

    struct aNode *current;
    current = (struct aNode *)malloc(sizeof(struct aNode));

    int buff = 120;
    char temp[buff];

    printf("Enter data: ");
    fgets(temp, buff, stdin);
    sscanf(temp, "%[^,]%*c %[^,]%*c %[^,]%*c %[^,]%*c %d%*c %f", 
           current->name, current->address, current->city, current->state,   
           &current->zip, &current->balance);                   

    insertSort(current);

    //only for testing
    printf("%s, %s, %s, %s, %5d, $%9.2f\n", 
            current->name, current->address, current->city, 
            current->state, current->zip, current->balance);
}

void print() {

    struct aNode *p;

    for(p = dLList; p != NULL; p = p->next) {
        printf("%s, %s, %s, %s, %5d, $%9.2f\n", 
               p->name, p->address, p->city, 
               p->state, p->zip, p->balance);
    }
}

//TODO
void delete() {

}

int insertSort(node * current) {

     struct aNode *p;
    struct aNode *q;

    p = (struct aNode *)malloc(sizeof(struct aNode));
    p = current;

    //need to link to previous node   
    if(dLList == NULL || strcmp(dLList->name, p->name) > 0) {
        p->next = dLList;
        p->prev = NULL;
        return(0);
    }else {
        q = dLList;
        while(q->next != NULL && strcmp(q->next->name, q->name) < 0) {
            q = q->next;
        }   
        p->next = q->next;
        q->next = p;
        return(0);
    }   
}

Вывод: Майк, 404 запрещенных ул, Роли, NC, 27607, $ 123,78

Не работает (с контролем пользователя):

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXNAMELEN 19
#define MAXADDRLEN 49
#define MAXCITYLEN 19
#define MAXSTATELEN 2

struct aNode {
    char name[MAXNAMELEN];
    char address[MAXADDRLEN];
    char city[MAXCITYLEN];
    char state[MAXSTATELEN];
    int zip;
    float balance;
    struct aNode *next;
    struct aNode *prev; 
};

typedef struct aNode node;
struct aNode *dLList;

void read();
void input();
void print();
void delete();
int insertSort(node*);

int main() {

    //from text file
    read();

    //input();

    int choice;
    while(1) {
        printf("\n1.INSERT\n2.DELETE\n3.DISPLAY\n4.END\n");
        printf("Enter choice:");
        scanf("%d",&choice);
        switch(choice) {
        case 1:
            input();
            break;
        case 2:
            delete();
            break;
        case 3:
            print();
            break;
        case 4:
            exit(0);
        }
    }

    return(0);
}

//TODO
void read() {

}

void input() {

    struct aNode *current;
    current = (struct aNode *)malloc(sizeof(struct aNode));

    int buff = 120;
    char temp[buff];

    printf("Enter data: ");
    fgets(temp, buff, stdin);
    sscanf(temp, "%[^,]%*c %[^,]%*c %[^,]%*c %[^,]%*c %d%*c %f", 
           current->name, current->address, current->city, current->state,   
           &current->zip, &current->balance);                   

    insertSort(current);

    //only for testing
    printf("%s, %s, %s, %s, %5d, $%9.2f\n", 
               current->name, current->address, current->city, 
               current->state, current->zip, current->balance);
}

void print() {

    struct aNode *p;

    for(p = dLList; p != NULL; p = p->next) {
        printf("%s, %s, %s, %s, %5d, $%9.2f\n", 
              p->name, p->address, p->city, 
              p->state, p->zip, p->balance);
    }
}

//TODO
void delete() {

}

int insertSort(node * current) {

     struct aNode *p;
    struct aNode *q;

    p = (struct aNode *)malloc(sizeof(struct aNode));
    p = current;

    //need to link to previous node   
    if(dLList == NULL || strcmp(dLList->name, p->name) > 0) {
        p->next = dLList;
        p->prev = NULL;
        return(0);
    }else {
        q = dLList;
        while(q->next != NULL && strcmp(q->next->name, q->name) < 0) {
            q = q->next;
        }   
        p->next = q->next;
        q->next = p;
        return(0);
    }   
}

Вывод:,,,, 0, $ 0.00

Ответы [ 2 ]

2 голосов
/ 27 апреля 2011

Проблема в том, что scanf не использует символ новой строки в конце строки выбора. Затем он читается с помощью вызова fgets в input(), поэтому входная строка пуста (кроме символа \n).

Это сработало для меня:

fgets(temp, buff, stdin);
sscanf(temp, "%d",&choice);
1 голос
/ 27 апреля 2011

Является ли dLList инициализируемым в NULL где-либо?
И если даже если это так, то не отображается установка первого узла при вставке нового узла в пустой список.

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