【发布时间】:2016-06-28 03:34:12
【问题描述】:
我编写了一个程序来将文件中的一组数据读入一个链表。程序从文件中读取一行,标记该行,将其存储到一个节点中,然后移动到下一行。每次执行此操作时,我都会打印节点的内容。我遇到的问题是,当程序运行时,它会在文件中的两行之一停止并崩溃。它比另一条更频繁地停在一条线上。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
typedef struct prefectNode
{
char *name; // prefect name
char *type; // prefect type
char *used;
struct free// structure storing the prefect's free sessions on particular days
{
char M[9];
char T[9];
char W[9];
char S[9];
char F[9];
} fses; // free sessions available to prefect;
struct prefectNode *nextPtr;// a pointer to the next node
} pNode;// Self-Referential structure used to store information about a prefect
typedef pNode *ptrNode;// Synonym for a pointer to a self-referential structure
void induct(ptrNode *list, char l[]);// induct is called when information is being retrieved from file.
void induct(ptrNode *list, char l[])
{
ptrNode curPtr = NULL;// pointer to the current node
ptrNode newPtr = malloc(sizeof(pNode));// creating new node
if (newPtr != NULL)
{
newPtr->name = strtok(l, ",");
newPtr->type = strtok(NULL, ",");
char *sesh = strtok(NULL, " ");
char c = sesh[0];
printf("%s\n%s\n", newPtr->name, newPtr->type);
int i = 0, j = 0;
for (i = 0; i < strlen(sesh); i++)
{
char c = sesh[i];
if (c == 'M')
{
newPtr->fses.M[j] = sesh[i + 1];
printf("M%c", newPtr->fses.M[j]);
}
if (c == 'T')
{
newPtr->fses.T[j] = sesh[i + 1];
printf("T%c", newPtr->fses.T[j]);
}
if (c == 'W')
{
newPtr->fses.W[j] = sesh[i + 1];
printf("W%c", newPtr->fses.W[j]);
}
if (c == 'S')
{
newPtr->fses.S[j] = sesh[i + 1];
printf("S%c", newPtr->fses.S[j]);
}
if (c == 'F')
{
newPtr->fses.F[j] = sesh[i + 1];
printf("F%c", newPtr->fses.F[j]);
}
i = i + 2;
j++;
}
newPtr->nextPtr = NULL;
curPtr = *list;
if (curPtr == NULL)
{
newPtr->nextPtr = *list;
*list = newPtr;
}
else
{
while (curPtr->nextPtr != NULL)
{
curPtr = curPtr->nextPtr;
}
curPtr->nextPtr = newPtr;
}
}
else
{
printf("no memory");
}
}
char ln[200];
FILE *fp;
int main()
{
ptrNode start = NULL;
fp = fopen("thefile.txt", "r");
if (fp == NULL)
{
printf("File not found.");
}
else
{
while (!feof(fp))
{
fgets(ln, sizeof(ln), fp);
induct(&start, ln);
printf("\n\n");
}
}
fclose(fp);
getch();
return 0;
}
这是输入文件的样例:
Denelia Alvaranga,R,M7_T4_T5_T6
Sainna Christian,R,M4_M5_M6_T1_T2_T3_F5_F6
Kashielle Clarke,R,F1_T4_W4_F4_T5_W5_S5_W6_S6_M7_W7
Candice Gordon,R,M1_M2_M3_S3_T7
Alphene Groves,R,M2_T5_S7_W3
T-Anna Johnson,R,M7
Vanessa Lewis,R,M1_M2_M3_S3_T4_W4_S4_T5_S5_T6_S6
当我到达第 9 行时,程序崩溃(更频繁):
Rhoni-Ann Parkins,R,W1_S1_W2_S2_W3_S3_M4_T4_S4_F4_M5_T5_F5_M6_T6_F6_T7_F7
或第 37 行:
Ashleigh Graham,N6A
【问题讨论】:
-
文件长约 85 行。
-
那么您的输入文件是什么样的,哪些是问题行??
-
那么,您是否在调试器中单步执行了代码?
-
我试过了,但是我的编译器的调试器不能工作,所以我试着不用它
-
这真是个坏主意。学习如何调试程序与学习语言一样重要。我建议您花一些时间来获得一个正常工作的开发环境。它会让生活更简单。