Wednesday, December 27, 2017

C++98: User-Defined Manipulators

You can write your own stream manipulators. Here is an example:

#include <iostream>
#include <istream>

template <class charT, class traits>
inline std::basic_istream<charT, traits>&
printNextChar(std::basic_istream<charT, traits>& stream)
{
  char nextChar;

  nextChar = std::cin.get();
  std::cin.unget();

  std::cout << nextChar;

  return stream;
}


int main()
{
  char myChar;

  std::cin >> printNextChar;
  std::cin >> myChar;

  std::cout << myChar << std::endl;

  return 0;
}
// Input: A
// Output: AA
Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, p. 614.

No comments:

Post a Comment