Is it possible to manipulate some text with a custom I / O manipulator?

Is there a (clean) way to manipulate some text from std :: cin before inserting it into std::string

so that the following will work:

cin >> setw(80) >> Uppercase >> mystring;

      

where is mystring std::string

(I don't want to use any string wrappers). Uppercase

- manipulator. I think it should act directly on the Chars in the buffer (whatever is currently considered uppercase and not lowercase). Such a manipulator seems tricky to implement in a clean way, as custom manipulators, as far as I know, are used to easily change or mix some predefined format flags.

+3


source to share


2 answers


(Short) manipulators usually set only flags and data, which the extractors then read and react to. (This requires xalloc

, iword

and pword

.) What you could obviously do is write something similar std::get_money

:

struct uppercasify {
  uppercasify(std::string &s) : ref(s) {}
  uppercasify(const uppercasify &other) : ref(other.ref) {}
  std::string &ref;
}
std::istream &operator>>(std::istream &is, uppercasify uc) { // or &&uc in C++11
  is >> uc.ref;
  boost::to_upper(uc.ref);
  return is;
}

cin >> setw(80) >> uppercasify(mystring);

      



Alternatively, it cin >> uppercase

can return not a reference to cin

, but an instance of some (template) wrapper class uppercase_istream

with an appropriate overload for operator>>

. I don't think it is a good idea to use a manipulator to change the contents of the underlying stream buffer.

If you're desperate enough, I think you could also imbue

create a localized locale that would result in the top lines. I don't think I would let something like this go through the code review, although it's just just waiting to surprise and bite the next person working on the code.

+3


source


You might want to check out boost iostreams. Its structure allows you to define filters that can control the flow. http://www.boost.org/doc/libs/1_49_0/libs/iostreams/doc/index.html



+3


source







All Articles