c++ - How to write a tester for a program that writes one bit at a time? -
i trying write tester following program see if functions correctly, however, i'm not sure if implemented flush() correctly , reason don't output. can suggest code test class see if implemented flush , writebit correctly?
#ifndef bitoutputstream_hpp #define bitoutputstream_hpp #include <iostream> class bitoutputstream { private: char buf; // 1 byte buffer of bits int nbits; // how many bits have been written buf std::ostream& out; // reference output stream use public: /* initialize bitoutputstream * use given ostream output. * */ bitoutputstream(std::ostream& os) : out(os) { buf = nbits = 0; // clear buffer , bit counter } /* send buffer output, , clear */ void flush() { out.put(buf); // edit: removed flush(); stop infinite recursion buf = nbits = 0; } /* write least sig bit of arg buffer */ int writebit(int i) { // if bit buffer full, flush it. if (nbits == 8) flush(); // write least significant bit of // buffer @ current index. // buf = buf << 1; option considering // buf |= 1 & i; decided go 1 below int lb = & 1; // extract lowest bit buf |= lb << nbits; // shift nbits , put in in buf // increment index nbits++; return nbits; } }; #endif // bitoutputstream_hpp
what wrote tester is:
#include "bitoutputstream.hpp" #include <iostream> int main(int argc, char* argv[]) { bitoutputstream bos(std::cout); // channel output 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); // prints 'a' ;) return 0; }
i know wrong since no output , have no way see if implementation correct. appreciate input can provide.
i compiled code with: g++ -std=c++11 main.cpp biooutputstream.hpp bitinputstream.cpp , ran with: ./a.out
- you're never calling
bitoutputstream::flush()
- add callbos.flush();
following callswritebit()
. - your
flush()
method recursive - calls itself, result in infinite loop. remove callflush()
within definition offlush()
. - your test won't print because single bit equate ascii value 1, isn't printable. try adding few more bits. e.g.
writebit(1); writebit(0); writebit(0); writebit(0); writebit(0); writebit(0); writebit(1);
should print a.
Comments
Post a Comment