如何为一次只写一位的程序编写测试程序
How to write a tester for a program that writes one bit at a time?
我正试图为下面的程序编写一个测试程序,看看它是否正常工作,但是,我不确定我是否正确地实现了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是否匹配。
相关文章:
- 一位朋友将模板函数缩写为clang和gcc
- 斐波那契数列部分和的最后一位数字
- 将第 n 个斐波那契数的大斐波那契数的最后一位编程.C++
- WinAPI C++如何从 64 位应用程序加载资源
- 使用 SysNative 在 Visual Studio 中创建 64 位应用程序
- 每(n)秒打印一次的程序
- 如何将参数传递给Google基准测试程序
- Cmake无法在qt-creater/collect2上编译简单的测试程序:错误:ld
- 如何检查 int 中是否恰好设置了一位?
- 如何找到由公式计算的非常大的数字的最后一位数字?
- CMake 和 Visual Studio 2015 - C 编译器 cl.exe 无法编译简单的测试程序
- C++编译器 g++.exe 无法编译简单的测试程序 - 确定 CXX 编译器是否工作失败
- 如何编译和运行 vmmlib 测试程序?
- C++测试程序中的非法系统调用(对角矩阵元素程序的总和)
- 在我的测试程序中,为什么 cv::resize 不能执行,而 cvtColor 可以?
- 使用 QtCreator 构建 CUDA/C++ 测试程序时出现错误 2
- 旧的 32 位 Linux 程序最终如何调用 64 位库
- 将32位和64位应用程序(具有相同代码)编译为一个EXE
- 在 64 位 Windows 上运行的 32 位应用程序是否仍然需要使用 SAFESEH 进行编译
- 如何为一次只写一位的程序编写测试程序