我正试图为下面的程序编写一个测试程序,看看它是否正常工作,但是,我不确定我是否正确地实现了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.输出
- 您从来没有实际调用过
BitOutputStream::flush()
—在调用writeBit()
之后再添加对bos.flush();
的调用 flush()
方法是递归的——它调用自己,这将导致一个无限循环。在flush()
的定义中删除对flush()
的调用- 您的测试可能不会打印任何内容,因为单个位将等于ASCII值1,而ASCII值1是不可打印的。尝试再添加一些位。例如,
writeBit(1); writeBit(0); writeBit(0); writeBit(0); writeBit(0); writeBit(0); writeBit(1);
应打印A
将对flush()
的条件调用放在writeBit()
的末尾,而不是开头。然后,您将在第8位之后进行自动刷新,而不是等到写入第9位。
为了测试您的代码,我会从stdin读取字节,按位将它们提供给writeBit,并检查inputfile和outputfile是否匹配。