2016-02-07 21 views
0

好的,所以我在处理一个项目时遇到了一些麻烦。我需要两个类来形成多变量类(或结构体)的链表。第一个称为gps的工作正常。它应该将x和y坐标读入一个位置,然后将其添加到链接列表中。这工作完全正常,看到如下:指针和类遇到问题。两个完全相同的课程,其中一个工作,一个不需要

ifstream in; 
location *tail = NULL; 
location *head = NULL; 

gps::gps() 
{ 
    tail = NULL; 

    in.open("coordinates.txt"); 
    if(in.fail()) 
    { 
     std::cout << "Unopen to open coordinates.txt" << std::endl; 
    } 
    while (!in.eof()) 
    { 
     getLocation(); 
    } 
    in.close(); 
} 

void gps::getLocation() 
{ 
    location o; 
    in >> o.xcoordinate; 
    in >> o.ycoordinate; 
    addToTail(o); 
} 

void gps::addToTail(location a) 
{ 
    location *newlocation = new location(); 
    newlocation->xcoordinate = a.xcoordinate; 
    newlocation->ycoordinate = a.ycoordinate; 
    newlocation->next = NULL; 

    if (tail == NULL) 
    { 
     head = tail = newlocation; 
    } 
    else 
    { 
     tail->next = newlocation; // now the next of old tail is the new location 
     tail = newlocation;  // the new location should become the new tail 
    } 
} 

所以这一切工作正常,但现在我需要相同的人做同样的事情,但它必须加速度的链接列表(x,y和z)从文件读取的值。但是,它会在崩溃之前返回第一组坐标。看看这两个类,它们看起来与用于存储数据的位置和加速类相同。为什么第一个工作,而第二个不工作?我觉得错误来自我的指针系统,但我无法弄清楚它有什么问题。 这里是传感器类,其中问题的根源:

ifstream in_2; 

sensor::sensor() 
{ 
    acceleration *head = NULL; 
    acceleration *tail = NULL; 



    in_2.open("acceleration.txt"); 
    if(in_2.fail()) 
    { 
     cout << "Unopen to open acceleration.txt" << std::endl; 
    } 
    while (!in_2.eof()) 
    { 
     getAcceleration(); 
    int f; 
    cin >> f; 
    } 
    in_2.close(); 
} 

void sensor::getAcceleration() 
{ 
    acceleration o; 
    in_2 >> o.x; 
    in_2>> o.y; 
    in_2>>o.z; 
    addToTail(o); 
} 

void sensor::addToTail(acceleration a) 
{ 
    acceleration *newacceleration = new acceleration(); 
    newacceleration->x = a.x; 
    newacceleration->y = a.y; 
    newacceleration->z = a.z; 
    newacceleration->next = NULL; 
    cout << a.x <<a.y<<a.z; 
    if (tail == NULL) 
    { 
     head = tail = newacceleration; 
    } 
    else 
    { 
     tail->next = newacceleration; // now the next of old tail is the new location 
     tail = newacceleration;  // the new location should become the new tail 
    } 

} 

我觉得错误介于绕线“COUT < < a.x < < a.y < < a.z;”因为这条线打印正确的值。希望有人能帮助我看看这里发生了什么!被卡住了很长时间。

编辑:

accelaration.txt:

1 1 1 
0 7 11 
1 7 10 
2 6 40 
1 7 -33 
0 7 12 

coordinates.txt:

53.344384 -6.261056 
    53.344424 -6.260818 
    53.344450 -6.260614 
    53.344476 -6.260324 
    53.344501 -6.260088 
    53.344537 -6.259906 
+0

您是否尝试过使用调试器? – erip

+0

将您的输入文件的一些行添加到问题 – Gavriel

+0

由于您没有提供真正的代码来尝试调试,因此我正在投票关闭此题作为题外话题。 – erip

回答

2

你有

newacceleration->y = a.y; 

两次。第二个必须是:

newacceleration->z = a.z; 

更新:什么是在传感器()这两行?

int f; 
cin >> f; 
+0

这是一个经典案例,其中[橡皮鸭](https://en.wikipedia.org/wiki/Rubber_duck_debugging)会帮助很多。 – erip

+0

对不起!这是帖子中的错字,而不是代码。感谢您指出。 –

相关问题