簡體   English   中英

從文件讀取和存儲屬性會產生錯誤的輸出

[英]Reading from file and storing attributes gives wrong output

我正在嘗試讀取包含以下三個屬性的文本文件;

RouterID,X坐標,Y坐標

下面顯示了txt文件的簡短片段;

100 0       0
1   20.56   310.47
2   46.34   219.22
3   240.40  59.52
4   372.76  88.95

現在,我想要實現的是為每個RouterID創建一個節點並存儲其相應的x和y坐標。 為此,我創建了以下類;

class Node {

public:
    float routerID;
    float x;
    float y;

    void set_rid (float routerID) {
        routerID = routerID;
    }

    void set_x_y (float x, float y) {
        x = x;
        y = y;
    }

};

我有以下執行為每個routerID創建一個新節點的工作;

const std::string fileName = "sampleInput.txt";
std::list<Node> nodeList;

int main (void) {

    std::ifstream infile(fileName);

    float a(0);
    float b(0), c(0);

    //This reads the file and makes new nodes associated with every input
    while (infile >> a >> b >> c) {
        Node newNode;
        newNode.set_rid (a);
        newNode.set_x_y (b, c);
        std::cout << "newNode " << "rid = " << newNode.routerID << " x = " << newNode.x << " y = " << newNode.y << std::endl;
        nodeList.push_back(newNode);
    }

我在while循環中執行以下行只是為了檢查分配的值是否正確。

std::cout << "newNode " << "rid = " << newNode.routerID << " x = " << newNode.x << " y = " << newNode.y << std::endl;

當我編譯並運行代碼時,我得到以下作為我所有輸出的輸出;

newNode rid = -1.07374e+008 x = -1.07374e+008 y = -1.07374e+008

我上周剛開始學習C ++,這是我嘗試編寫的第一個“大”程序。 有誰能請我指出正確的方向?

void set_rid (float routerID) {
    routerID = routerID;
}

這不符合你的想象。 它將參數分配給自己; this->routerID的值保持不變。 set_x_y相同。 只需為方法參數指定一些與數據成員不同的名稱。

另一個將類變量與輸入參數區分開來的方法是使用關鍵字this。 因此,您可以通過調用this.routerID,this.x和this.y來引用類變量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM