【发布时间】:2016-01-02 17:21:12
【问题描述】:
我正在尝试读取文本数据行,并将它们存储在链接列表中。 输入数据如下所示:
David Copperfield
Charles Dickens
4250
24.95
32.95
10
6
END_DATA
我读取数据的方式是先读取第一行,看是不是END_DATA。如果不是,那么我将第一行传递给一个函数,该函数创建一个链接列表节点,其中包含书籍数据。出于某种原因,在我将第一行传递给函数后,scanf 不会读取第二行。
当我在节点读取数据后尝试打印节点时,我的输出如下所示。
David Copperfield
0
0.000000
0.000000
0
0
Charles Dickens
4250
24.950001
32.950001
10
6
Charles Dickens
0
0.000000
0.000000
0
0
源码如下
#include "lab3p1.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct NodeRec {
Book data;
struct NodeRec *next;
};
typedef struct NodeRec Node;
float findRevenue(Node *head);
float totalWholesaleCost(Node *head);
float totalProfit(Node *head);
float totalBooksSold(Node *head);
float averageProfitPerSale(Node *head);
void printNodes(Node *head);
void insertNode(Node* head, Node* newNode);
Node* createNewNode(char titleS[40]) {
Node* newNode;
newNode = malloc(sizeof(Node));
if (newNode == NULL){
printf("ERROR ALLOCATING SPACE");
exit(-1);
}
else {
strcpy(newNode->data.title, titleS);
scanf("%40[^\n]*c", (char *)&newNode->data.author);
scanf ("%i %f %f %i %i", &newNode->data.number, &newNode->data.wholesaleprice, &newNode->data.retailprice, &newNode->data.wholesalequantity, &newNode->data.retailquantity);
printf ("%s \n%s \n%i \n%f \n%f \n%i \n%i\n", newNode->data.title, newNode->data.author,newNode->data.number, newNode->data.wholesaleprice, newNode->data.retailprice, newNode->data.wholesalequantity, newNode->data.retailquantity);
}
return newNode;
}
void readBooks(Node* head) {
char firstline[40];
char enddataString[40] = "END_DATA";
scanf("%40[^\n]*c", (char *)&firstline);
while (strcmp(firstline, enddataString)) {
Node* newNode = createNewNode(firstline);
insertNode(head, newNode);
scanf("%40[^\n]*c", (char *)&firstline);
}
}
void insertNode(Node* head, Node* newNode) {
if (head == NULL) {
head = newNode;
}
else {
Node *preNode, *currentNode;
int n = newNode->data.number;
currentNode = head;
while (currentNode != NULL && (currentNode->data.number) > n ) {
preNode = currentNode;
currentNode = currentNode->next;
}
newNode->next = currentNode;
preNode->next = newNode;
}
}
【问题讨论】:
-
1) 检查来自
scanf()的结果 2) 添加空格scanf(" %39[^\n]*c" ...3) (40 --> 39)。 GTG Some 可以详细说明这一点。 -
我非常爱你。为什么这些空间有效??
标签: c struct linked-list scanf