作者LiuLiuiris (Pipi)
看板C_and_CPP
標題[問題] link_list指標
時間Fri Feb 25 16:55:47 2011
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
c++
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
none
問題(Question):
ptr指標有錯誤,ptr->name或ptr->count都會出現錯誤
餵入的資料(Input):
3
This is a test.
Count me 1 2 3 4 5.
Wow!!!! Is this question easy?
2
Good luck!
Pass.
0
預期的正確結果(Expected Output):
S 7
T 6
I 5
E 4
O 3
A 2
H 2
N 2
U 2
W 2
C 1
M 1
Q 1
Y 1
O 2
S 2
A 1
C 1
D 1
G 1
K 1
L 1
P 1
U 1
錯誤結果(Wrong Output):
指標有問題
程式碼(Code):(請善用置底文網頁, 記得排版)
#include<iostream>
#include<iomanip>
#include<cstdio>
#include<cstdlib>
#include <fstream>
using namespace std;
typedef struct list
{
int name;
int count;
struct list *next;
}node;
int main()
{
FILE *fp = fopen( "letter.txt", "r" ) ;
if(!fp){ cout << "讀檔失敗" << endl; }
int data,clt,change,sum;
char wd;
fscanf(fp,"%d",&data);
while(data) //data為0終止程式
{
node *head = NULL;
node *tail;
node *new_node;
clt = data+1;
while(clt) //判斷換行次數
{
fscanf(fp,"%c",&wd);
change = (int)wd;
if(change==10) clt--; //換行字元
else //一般字元
{
if((change>64&&change<91)||(change>96&&change<123))
{
if(head==NULL) //鏈結為空
{
if((122-change)<26) //小寫
{
new_node=(node *)malloc(sizeof(node));
new_node->name = change-96;
new_node->count = 1;
new_node->next = head;
head = new_node;
tail = head;
}
else //大寫
{
new_node=(node *)malloc(sizeof(node));
new_node->name = change-64;
new_node->count = 1;
new_node->next = head;
head = new_node;
tail = head;
}
}
else //鏈結不為空
{
node *ptr;
ptr = head;
if((122-change)<27) //小寫
{
while((ptr!=NULL)&&(ptr->name!=change))
{
ptr = ptr->next;
}
if(ptr==NULL)
{
new_node=(node *)malloc(sizeof(node));
new_node->name = change-96;
new_node->count = 1;
new_node->next = tail->next;
tail->next = new_node;
tail = new_node;
}
else
{
sum = ptr->count + 1;
ptr->count = sum;
}
}
else //大寫
{
while((ptr!=NULL)&&(ptr->name!=change))
{
ptr = ptr->next;
}
if(ptr==NULL)
{
new_node=(node *)malloc(sizeof(node));
new_node->name = change-64;
new_node->count = 1;
new_node->next = tail->next;
tail->next = new_node;
tail = new_node;
}
else
{
sum = ptr->count + 1;
ptr->count = sum;
}
}
}
}
}
}
/*node *temp;
temp = head;
for(temp;temp!=tail;temp->next)
{
cout << head->name;
}*/
fscanf(fp,"%d",&data);
}
system("pause");
return 0;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.130.175.165
→ legnaleurc:好像強迫自己用C++又回去用C的寫法 02/25 17:05
→ legnaleurc:這個其實用陣列會比較好做 02/25 17:05
→ loveme00835:一個main...現在是在做 word count? 02/25 17:07
→ james732:一大堆的magic number看得我頭好痛啊 XD 02/25 17:35
→ legnaleurc:ctypes 是你的好朋友 :P 02/25 17:36
→ james732:if((122-change)<27) //小寫 <=這種程式碼讓人很頭痛呢 02/25 17:40
→ james732:也建議學習debugger如何使用,一步一步的找錯誤 02/25 17:46