I have a feeling ya'll get plenty of cin questions here and are quit tired of them, but I have a few that are a little more in depth. I started trying to write my own input stream flush template and had some very minor successes when I found the sticky at the top of this and found a break through. Here is what I wrote after the breakthrough
template <typename CharT>
void flush(std::basic_istream<CharT> &in)
{
in.clear();
char nextChar= in.get();
while(nextChar != '\n' && nextChar != std::char_traits<CharT>::eof())
nextChar= in.get();
in.clear();
}
template <typename CharT, typename var_type>
void extractr(std::basic_istream<CharT> &in, var_type &var, bool FLUSH= false)
{
if(!in)
flush(in);
in >> var;
while(!in)
{
cout << "\nInvalid data type, please enter a " << typeid(var).name() << endl << "-> ";
flush(in);
in >> var;
}
if(FLUSH)
flush(in);
}
I played around with the solution the sticky offered and got to this, but it doesn't work in my codes.
template <typename CharT>
void ignore_line(std::basic_istream<CharT> &in)
{
in.clear();
if(in.rdbuf()->sungetc() != std::char_traits<CharT>::eof() && in.get() != '\n')
in.ignore(std::numeric_limits<std::streamsize>::max(), in.widen('\n'));
in.clear();
}
Question 1) What exactly does widen() do? I've seen it several times but don't really understand what it is accomplishing.
Question 2) Why does the first one work perfectly but the second one not fix the input stream?