我正在为一个大学项目编写此代码,我需要将此文本文件加载到单链接列表中。但是在打印时,它仅打印文件的第一行(LinkedList中的第一个节点)。 .txt文件中的行如下:
大众高尔夫2017白色120000
大众高尔夫2017黑色121000
大众POLO 2018橙色95000
大众CADDY 2015黑色145000
大众CADDY 2015黑色145000等。
任何帮助将不胜感激,谢谢! 查看代码:
struct sCar{
char manufacturer[15];
char model[15];
int year;
char colour[10];
float price;
struct sCar *nextInLine;
};
//Changing name for convenience.
typedef struct sCar * LIST;
typedef struct sCar * NODE;
int main()
{
printf("\n\n** START **\n\n");
LIST carsList;
carsList = MakeEmpty(NULL); //Initialized. (carsList) is now the Head.
NODE temp;
temp = (NODE)malloc(sizeof(struct sCar));
FILE *fPtr;
if ((fPtr = fopen("cars.dat", "r")) == NULL)
puts("File could not be opened");
else
{
fscanf(fPtr, "%s %s %d %s %f", &temp->manufacturer, &temp->model,
&temp->year, &temp->colour, &temp->price);
if(carsList->nextInLine == NULL)
{
carsList->nextInLine = temp;
temp->nextInLine = NULL;
}
else
while(fscanf(fPtr, "%s %s %d %s %f", &temp->manufacturer, &temp->model, &temp->year, &temp->colour, &temp->price) == 5)
{
NODE newNode;
newNode = (NODE)malloc(sizeof(struct sCar));
fscanf(fPtr, "%s %s %d %s %f", &newNode->manufacturer, &newNode->model, &newNode->year, &newNode->colour, &newNode->price);
temp->nextInLine = newNode;
temp = newNode;
temp->nextInLine = NULL;
}
}
printNodes(carsList);
return 0;
}
LIST MakeEmpty(LIST L)
{
if(L != NULL)
DeleteList(L);
L = NULL;
L = (LIST)malloc(sizeof(struct sCar));
if(L==NULL)
printf("Out of Memory. Can't Allocate List.");
else
L->nextInLine = NULL;
return L;
}
void printNodes(LIST L)
{
LIST temp;
temp = L->nextInLine;
while(temp != NULL)
{
printf("\n\nManufacturer: %s", temp->manufacturer);
printf("\nModel: %s", temp->model);
printf("\nYear: %d", temp->year);
printf("\nColour: %s", temp->colour);
printf("\nPrice: %.2f\n", temp->price);
temp = temp->nextInLine;
}
}
答案 0 :(得分:0)
struct sCar {
char manufacturer[15];
char model[15];
int year;
char colour[10];
float price;
struct sCar *nextInLine;
};
typedef struct sCar * LIST;
typedef struct sCar * NODE;
void printNodes(LIST L)
{
while(L != NULL) {
printf("\n\nManufacturer: %s", L->manufacturer);
printf("\nModel: %s", L->model);
printf("\nYear: %d", L->year);
printf("\nColour: %s", L->colour);
printf("\nPrice: %.2f\n", L->price);
L = L->nextInLine;
}
}
int main()
{
printf("\n\n** START **\n\n");
LIST carsList;
carsList = malloc(sizeof(struct sCar));
FILE *fPtr;
if((fPtr = fopen("cars.dat", "r")) == NULL)
puts("File could not be opened");
else
{
NODE NEXT = carsList;
while(NEXT != NULL && fscanf(fPtr, "%s %s %i %s %f", &(*NEXT->manufacturer), &(*NEXT->model), &(*NEXT).year, (*NEXT).colour, &(*NEXT).price) != EOF) {
NODE newNode;
newNode = (NODE)malloc(sizeof(struct sCar));
NEXT->nextInLine = newNode;
NEXT = newNode;
}
printNodes(carsList);
}
}
我将它留给您,以了解您如何停止循环。控制台上打印的最后一项是没有设置任何字段的空sCar。