简体   繁体   English

从文件读取和存储属性会产生错误的输出

[英]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 . RouterID,X坐标,Y坐标

A brief snippet of the txt file is shown below; 下面显示了txt文件的简短片段;

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. 现在,我想要实现的是为每个RouterID创建一个节点并存储其相应的x和y坐标。 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; 我有以下执行为每个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. 我在while循环中执行以下行只是为了检查分配的值是否正确。

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. 我上周刚开始学习C ++,这是我尝试编写的第一个“大”程序。 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. this->routerID的值保持不变。 Same with set_x_y . 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. 另一个将类变量与输入参数区分开来的方法是使用关键字this。 thus you can make a reference to class variables by calling this.routerID, this.x and this.y 因此,您可以通过调用this.routerID,this.x和this.y来引用类变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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