好的,所以我在處理一個項目時遇到了一些麻煩。我需要兩個類來形成多變量類(或結構體)的鏈表。第一個稱爲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
您是否嘗試過使用調試器? – erip
將您的輸入文件的一些行添加到問題 – Gavriel
由於您沒有提供真正的代碼來嘗試調試,因此我正在投票關閉此題作爲題外話題。 – erip