c++ - 从文件中读取和存储属性会给出错误的输出

标签 c++ file-io nodes

我正在尝试读取包含以下三个属性的文本文件;

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 相同。只需给方法参数一些不同于数据成员的名称即可。

关于c++ - 从文件中读取和存储属性会给出错误的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17666198/

相关文章:

c++ - 为什么我在此函数中出现段错误?

c - fscanf 不能正常工作

node.js - 使用 require grunt 找不到模块 'coffee-script'

javascript - 使用 vue 分布式文件中定义的函数

c++ - 如果你给一个指针加1,它是真的加1,还是加4或32?

c++ - 成员函数指针作为构造函数参数

c++ - 在 C++ 中实现二进制信号量类

matlab - 在matlab中读取.yml文件

c# - 输入不是有效的 Base64 字符串,因为它包含非 base 64 字符

java - 广度优先树