Wednesday, December 27, 2017

C++98: The boolalpha and nobool alpha Manipulators on cin

The boolalpha manipulator changes the way Boolean values are input from cin. Here is an example:

#include <iostream>

int main()
{
  bool dTrue   = false;
  bool dFalse  = false;
  bool szTrue  = false;
  bool szFalse = false;

  std::cin >> std::boolalpha;

  std::cin >> dTrue;
  std::cin >> dFalse;
  std::cin >> szTrue;
  std::cin >> szFalse;

  std::cout << dTrue   << " "; // 1
  std::cout << dFalse  << " "; // 0
  std::cout << szTrue  << " "; // 1
  std::cout << szFalse << " "; // 0

  std::cin >> std::noboolalpha;

  std::cin >> dTrue;
  std::cin >> dFalse;
  std::cin >> szTrue;
  std::cin >> szFalse;

  std::cout << dTrue   << " "; // 1
  std::cout << dFalse  << " "; // 0
  std::cout << szTrue  << " "; // 1
  std::cout << szFalse << " "; // 0

  std::cout << std::endl;
  return 0;
}
// Input : true false true false 1 0 1 0
// Output: 1 0 1 0 1 0 1 0
Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, p. 617.

No comments:

Post a Comment