0

我正在尝试为以下程序编写一个测试程序,以查看它是否正常运行,但是,我不确定我是否正确实现了 flush() 并且由于某种原因我没有得到任何输出。有人可以建议代码来测试这个类,看看我是否正确实现了flush和writeBit?

#ifndef BITOUTPUTSTREAM_HPP
#define BITOUTPUTSTREAM_HPP
#include <iostream>

class BitOutputStream {

private: 
  char buf;             // one byte buffer of bits
  int nbits;            // how many bits have been written to buf
  std::ostream& out;    // reference to the output stream to use

public:
  /* Initialize a BitOutputStream that will 
   * use the given ostream for output. 
   * */
  BitOutputStream(std::ostream& os) : out(os) {
    buf = nbits = 0;    // clear buffer and bit counter
  }

  /* Send the buffer to the output, and clear it */
  void flush() {
  out.put(buf);
  // EDIT: removed flush(); to stop the infinite recursion
  buf = nbits = 0;
  }


  /* Write the least sig bit of arg into buffer */
  int writeBit(int i) {
  // If bit buffer is full, flush it.
  if (nbits == 8) 
    flush();

// Write the least significant bit of i into 
// the buffer at the current index.
// buf = buf << 1;  this is another option I was considering
// buf |= 1 & i;    but decided to go with the one below

  int lb = i & 1;      // extract the lowest bit
  buf |= lb << nbits;  // shift it nbits and put in in buf

  // increment index
  nbits++;

  return nbits;
  }
};

#endif // BITOUTPUTSTREAM_HPP

我作为测试人员写的是:

#include "BitOutputStream.hpp"
#include <iostream>

int main(int argc, char* argv[])
{
  BitOutputStream bos(std::cout);  // channel output to stdout
  bos.writeBit(1);
  // Edit: added lines below
  bos.writeBit(0);
  bos.writeBit(0);
  bos.writeBit(0);
  bos.writeBit(0);
  bos.writeBit(0);
  bos.writeBit(0);
  bos.writeBit(1);

  // now prints an 'A' ;)

  return 0;
}

我知道这是错误的,因为我没有得到任何输出并且无法查看实现是否正确。感谢您提供的任何意见。

我用: g++ -std=c++11 main.cpp BioOutputStream.hpp BitInputStream.cpp 编译了代码并用: ./a.out 运行它

4

2 回答 2

0

将您的条件调用flush()放在 末尾writeBit(),而不是开头。然后您将在第 8 位之后自动刷新,而不是等到您写入第 9 位。

为了测试您的代码,我将从标准输入读取字节,将它们按位提供给 writeBit,并检查输入文件和输出文件是否匹配。

于 2013-08-24T04:17:33.190 回答
0
  1. 你从来没有真正打电话BitOutputStream::flush()- 添加一个电话来bos.flush();关注你对writeBit().
  2. 您的flush()方法是递归的 - 它调用自身,这将导致无限循环。删除对flush()的定义内的调用flush()
  3. 您的测试可能不会打印任何内容,因为单个位将等同于 ASCII 值 1,这是不可打印的。尝试添加更多位。例如writeBit(1); writeBit(0); writeBit(0); writeBit(0); writeBit(0); writeBit(0); writeBit(1);应该打印一个 A。
于 2013-08-24T03:11:48.597 回答