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 番目のビットを書き込むまで待機しません。

コードをテストするには、stdin からバイトを読み取り、ビット単位で writeBit にフィードし、inputfile と outputfile が一致するかどうかを確認します。

于 2013-08-24T04:17:33.190 に答える