【问题标题】:Bool: Incorrect output of cout not 0 or 1Bool:cout 的错误输出不是 0 或 1
【发布时间】:2012-10-30 17:42:12
【问题描述】:

我有一个读取请求的函数:按时间戳、当前楼层和目标楼层,但它没有按我预期的方式输出。

我的所有成员值都正确输出:时间戳、当前楼层和目标楼层,布尔值除外。

bool 输出 205 而不是我的方向的 1 或 0。

Elevator::readRequests()

{
  ifstream myStream("T1.txt");

while(!myStream.eof())
{
    int timestamp ,currentFloor, destinationFloor;


    myStream >> timestamp >> currentFloor >> destinationFloor;
    //cout<< endl <<"The current timestamp is "<< timestamp << "The current floor is " << currentFloor 
    //  << " and the destination floor is " << destinationFloor << endl << endl;
    //cout<< endl;

    reqNode *temp = new reqNode;

    //initialize request node object
    temp->timestamp = timestamp;
    temp->start = currentFloor;
    temp->destination = destinationFloor;
    temp->start_time = -1;
    temp->finish_time = -1;

    temp->calculate_priority();

    if(temp->start < temp->destination)
        temp->set_dir(true);
    else
        temp->set_dir(false);

    request.push(*temp);//push nodes into the request bank
}
int i = 0;
while( !request.empty() )
{

    cout << "Node " << i << " : " << request.front().timestamp << " " <<    request.front().start << " " << request.front().destination
        << " " <<  request.front().direction << endl;

    request.pop();//popping the request in order to test
    i++;
}


}

我正在尝试获取输出:

节点号:时间戳。当前(用户楼层)。目的地(用户楼层)。方向(用户正在前进)。

Node 0 : 1 3 7 1
Node 1 : 1 2 9 1
Node 2 : 1 7 9 1
Node 3 : 2 4 6 1
Node 4 : 2 4 8 1
Node 5 : 2 1 17 1
Node 6 : 5 1 15 1
Node 7 : 5 5 1 0
Node 8 : 6 17 4 0
Node 9 : 6 4 17 1

相反,我得到的是输出:

Node 0 : 1 3 7 205
Node 1 : 1 2 9 205
Node 2 : 1 7 9 205
Node 3 : 2 4 6 205
Node 4 : 2 4 8 205
Node 5 : 2 1 17 205 
Node 6 : 5 1 15 205
Node 7 : 5 5 1 205
Node 8 : 6 17 4 205
Node 9 : 6 4 17 205

这是文件 T1.txt:

1 3 7
1 2 9
1 7 9
2 4 6
2 4 8
2 1 17
5 1 15
5 5 1
6 17 4
6 4 17

【问题讨论】:

  • 请出示reqNode的代码。
  • 也许我是盲人,但我在任何地方都看不到bool..

标签: c++ boolean cout


【解决方案1】:

205 是0xCD。这通常意味着您使用的是未初始化的变量。

根据原题中的代码,需要在reqNode的复制构造函数中复制direction。根据输出,它没有被复制。

此外,由于您的向量似乎是vector&lt;reqNode&gt;,因此您无需将临时reqNode 分配给new。只需在堆栈上创建它并将其传递给requests.push_back。

【讨论】:

    【解决方案2】:

    request.push(*temp) 复制temp 指向的对象。作为风格问题,您应该在执行此操作后删除指针,因为不再需要该对象。更好的是,将其创建为自动对象而不是新建它。 C++ 不是 Java。

    由于存储的副本与原始副本的值不同,这表明 reqNode 的复制构造函数没有正确复制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-25
      • 2021-07-23
      • 2020-08-15
      • 2017-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多