作者Linkzibata12 (XXXXX)
看板C_and_CPP
標題[問題] linkedlist 排序問題
時間Sun Oct 28 11:15:20 2018
開發平台(Platform): (Ex: Win10, Linux, ...) Win10
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)Visual Stdio
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question): 無法跑出來
餵入的資料(Input): https://i.imgur.com/7jHDGkW.jpg讀入一筆文件 用linkedlist
預期的正確結果(Expected Output): 價錢小到大
錯誤結果(Wrong Output):正常版可以 價錢版無法
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
int id;
char product[50];
int price;
struct node *next;
}NODE;
NODE *head,*pre,*ptr,*temp;
void main()
{
head=(NODE*)malloc(sizeof(NODE));
head->next=NULL;
temp=(NODE*)malloc(sizeof(NODE));
FILE *fptr1;
fptr1= fopen("A.txt","r");
while (fscanf(fptr1,"%d %s %d",&temp->id,temp->product,&temp->price)==3
{
temp->next=head->next;
head->next=temp;
printf("ID:%d,product:%s,price:%d",temp->id,temp->product,temp->
printf("\n");
}
printf("-----------------------------------------------------------\n");
ptr=(NODE*)malloc(sizeof(NODE));
temp=(NODE*)malloc(sizeof(NODE));
ptr=(NODE*)malloc(sizeof(NODE));
while (fscanf(fptr1,"%d %s %d",&ptr->id,ptr->product,&ptr->price)==3)
{
pre=head;
temp=head->next;
while((temp!= NULL)&&(temp->price > ptr->price))
{
pre=temp;
temp=temp->next;
}
ptr->next=temp;
pre->next=ptr;
printf("ID:%d,product:%s,price:%d",ptr->id,ptr->product,ptr->price);
printf("\n");
}
fclose(fptr1);
system("pause");
}
補充說明(Supplement):不好意思 想請問大家我的程式碼哪裡有錯 正常
版的有印出來 可是依照價錢大小的卻無法都是空白的 初學者不太懂不好意思
網址程式碼
https://paste.ofcode.org/k9teTMqT8ABe24KHyN32wj
----
Sent from
BePTT
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 117.19.147.104
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1540696523.A.DB0.html
※ 編輯: Linkzibata12 (117.19.147.104), 10/28/2018 11:19:03
※ 編輯: Linkzibata12 (117.19.147.104), 10/28/2018 11:21:12
※ 編輯: Linkzibata12 (117.19.147.104), 10/28/2018 11:24:02
推 achicn3: 在你第一個while迴圈 fptr已指向檔案結尾了10/28 11:29
※ 編輯: Linkzibata12 (117.19.147.104), 10/28/2018 11:30:00
→ achicn3: 使用rewind(fptr)10/28 11:30
不太懂怎麼下手QQ
※ 編輯: Linkzibata12 (117.19.147.104), 10/28/2018 11:35:35
推 uorol: 首先把你的排版給排好10/28 12:24
推 uorol: 再來你知道你的程式碼在幹嘛嗎10/28 12:29
→ uorol: 你知道你第二個while環圈呼叫fscanf(fptr1...)在幹嘛嗎10/28 12:29
不好意思 請問是我那一個while的條件要重寫嗎?
※ 編輯: Linkzibata12 (117.19.147.104), 10/28/2018 12:47:12
※ 編輯: Linkzibata12 (117.19.147.104), 10/28/2018 12:51:22
※ 編輯: Linkzibata12 (117.19.147.104), 10/28/2018 12:55:49
推 uorol: 你沒有回答問題阿 如果你根本不知道你在寫啥, 要別人怎麼幫 10/28 17:37
→ uorol: 如果你只是要解答, 上面的版友已經說了 10/28 17:38
推 uorol: 因為你問的不是程式問題, 而是邏輯問題 10/28 17:41
→ c910335: 所有輸入都被寫進同一個node也是個問題 10/29 16:10