我正在尝试为以下程序编写测试程序以查看它是否正常运行,但是,我不确定我是否正确实现了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
答案 0 :(得分:0)
BitOutputStream::flush()
- 在致电bos.flush();
后致电writeBit()
。flush()
方法是递归的 - 它调用自身,这将导致无限循环。在flush()
。flush()
的号召
writeBit(1); writeBit(0); writeBit(0); writeBit(0); writeBit(0); writeBit(0); writeBit(1);
应打印A。答案 1 :(得分:0)
在flush()
结束时将条件调用发送到writeBit()
,而不是在开头。然后你会在第8位之后自动刷新,而不是等到你写第9位。
为了测试你的代码,我会从stdin中读取字节,将它们按位写入writeBit,并检查inputfile和outputfile是否匹配。