简体   繁体   中英

Reading from file and storing attributes gives wrong output

I'm trying to read a text file that consists of the following three attributes;

RouterID, X-coordinate, Y-coordinate .

A brief snippet of the txt file is shown below;

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

Now, what I'm trying to achieve is to make a node for every RouterID and store its corresponding x and y co-ordinates. For this purpose, I have created the following class;

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;
    }

};

And I have the following which performs the job of creating a new node for every 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);
    }

I'm performing the following line inside my while loop just to check whether or not the values being assigned are correct or not.

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

When I compile and run the code, I get the following as my output for all of them;

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

I've just started learning C++ last week and this is my first "big" program that I am trying to code. Could anyone please point me in the right direction?

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

This doesn't do what you seem to think it does. It assigns the parameter to itself; the value of this->routerID remains unchanged. Same with set_x_y . Just give the method parameters some names that are different from those of data members.

Another to distinguish class variables from input parameter is by using the keyword this. thus you can make a reference to class variables by calling this.routerID, this.x and this.y

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM