fork download
  1. #include <sstream>
  2. #include <string>
  3. #include <bitset>
  4. #include <iostream>
  5. #include <iomanip>
  6.  
  7. int main()
  8. {
  9. const std::string test[] = { "...|N|Y|N|N|...", "...|Y|N|Y|N|...", "...|N|Y|Y|N|..." } ;
  10.  
  11. for( const std::string& str : test )
  12. {
  13. std::istringstream stm(str) ;
  14.  
  15. // parse the four Y/N into bool values
  16. // and form a bitset of four bits with with 'Y' == 1
  17.  
  18. constexpr std::size_t NBITS = 4 ;
  19. std::bitset<NBITS> bits ; // set of four bits
  20. char Y_or_N ;
  21. for( std::size_t i = 0 ; i < NBITS ; ++i )
  22. {
  23. stm.ignore( 100, '|' ) ; // throw characters away upto and including the next '|'
  24. stm >> Y_or_N ; // read the next char ('Y' or 'N')
  25. bits[ (NBITS-1) - i ] = Y_or_N == 'Y' ; // set the corrosponding bit to 1 if it is a 'Y'
  26. }
  27.  
  28. // get the code by converting the bits to an integral value
  29. auto code = bits.to_ulong() ;
  30.  
  31. // check it out
  32. std::cout << str << " " << bits << " " << std::setw(2) << std::setfill('0') << code << '\n' ;
  33. }
  34. }
  35.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
...|N|Y|N|N|...  0100  04
...|Y|N|Y|N|...  1010  10
...|N|Y|Y|N|...  0110  06