第一个问题解决后,我又遇到了另一个问题。它发生在while循环
while (!infile.eof())
时的结果相同
while (getline(infile, line))
似乎不知何故它无法检查条件或某事,然后它再次崩溃。
[以下部分已解决]
这是功能。插入吨cout后看看发生了什么,这个
curr->prev = a->start;
是该行导致运行时错误。整个功能在这里:
busRoute readlist(const char* filename)
{
busRoute *a;
a = new busRoute; //a new bus route
stop_pointer curr;
stop_pointer pre;
fstream infile;
infile.open(filename);
string route="";
string line="";
int i=0;
float df, ef;
if (infile.is_open())
{
getline(infile, route); //read route number in string
a->routeNo=atoi(route.c_str()); //convert and store route num in int
while (!infile.eof())
{
i++;
getline(infile, line);//read text
//generate linked list
unsigned int pos;
string b,c,d,e;
pos = line.find(",");
if (pos <100000)
{
b = line.substr(0,pos); //stop name
c = line.substr(pos+1, line.length()-pos+2);
pos = c.find(",");
d = c.substr(0, pos); //latitude in string
e = c.substr(pos+1, c.length()-pos+2); //longitude in string
df = atof (d.c_str()); //latitude in float
ef = atof (e.c_str()); //longitude in float
//store b c d e into a
if (i<2)
{
a->start->stop_name= b;
a->start->latitude=df;
a->start->longitude=ef;
a->start->prev=NULL;
curr = a->start->next;
//sth wrong with curr->prev
curr->prev = a->start;
}
else
{
curr->stop_name=b;
curr->latitude=df;
curr->longitude=ef;
curr->next = new stop_node;
pre = curr;
curr = curr->next;
curr->prev = pre;
}
}
}
infile.close();
}
return *a;
}
以下是.h
typedef struct stop_node* stop_pointer;
typedef struct stop_node {
string stop_name; // the name of the stop
float latitude; // the latitude of the geographic coordinates of the stop
float longitude; // the longitude of the geographic coordinates of the stop
stop_pointer next; // the next pointer
stop_pointer prev; // the prev pointer
};
typedef struct busRoute {
int routeNo; // the route number of the stop
stop_pointer start; // the head of the linked list
};
有人可以向我解释我犯了什么错误吗?非常感谢你。
答案 0 :(得分:1)
我认为a->start->next;
第一次指向一些垃圾值......
所以当你尝试
时curr = a->start->next;
所以在这里你要为curr分配垃圾值
curr->prev = a->start;
在这里你试图访问无效的位置导致运行时错误。希望这会有所帮助......
///为使代码工作所做的更改......
if (i<2)
{
a->start->stop_name= b;
a->start->latitude=df;
a->start->longitude=ef;
a->start->prev=NULL;
//adding
a->start->next=NULL;
curr = a->start;
}
else
{
curr->next=new stop_node;
curr->next->prev=curr;
curr->stop_name=b;
curr->latitude=df;
curr=curr->next;
curr->next= NULL;
}
结构声明存在问题......
删除此
//typedef struct stop_node* stop_pointer;
typedef struct stop_node {
string stop_name; // the name of the stop
float latitude; // the latitude of the geographic coordinates of the stop
float longitude; // the longitude of the geographic coordinates of the stop
stop_node *next; // the next pointer
stop_node *prev; // the prev pointer
};
typedef struct busRoute {
int routeNo; // the route number of the stop
//stop_pointer start; // the head of the linked list
stop_node start;
};
如果start
是指针类型;你需要动态分配内存然后访问内存。所以它会像这样
a-&gt; start = new bus_node();
为避免并发症,请使用上面的struct和Use定义。运算符访问其余代码中的start成员。例如。 a->start.next = NULL