To understand how input streams work I designed 2 of the following classes:
#include <iostream>
class my_streambuf: public std::streambuf
{
private:
std::streambuf* buffer;
char ch;
protected:
virtual std::streambuf::int_type underflow()
{
std::streambuf::int_type result = buffer->sbumpc();
if (result != traits_type::eof())
{
ch = traits_type::to_char_type(result);
setg(&ch, &ch, &ch + 1);
}
return result;
}
public:
my_streambuf(std::streambuf* buffer) : buffer(buffer) {};
virtual ~my_streambuf() {};
};
class my_istream: public std::istream
{
public:
my_istream(std::istream& stream) : std::istream(new my_streambuf(stream.rdbuf())) {};
virtual ~my_istream()
{
delete rdbuf();
}
};
int main()
{
char s[32];
my_istream is(std::cin);
is >> s;
std::cout << s;
return 0;
}
Which work fine, until I change the logic of underflow
method. The primary goal is to save data in c-string valiable s
which differs from user-input. To make a simple test, I changed the underflow
method to be the following:
virtual std::streambuf::int_type underflow()
{
std::streambuf::int_type result = buffer->sbumpc();
if (result != traits_type::eof())
{
result = traits_type::to_int_type('+'); // <-- this was added
ch = traits_type::to_char_type(result);
setg(&ch, &ch, &ch + 1);
}
return result;
}
With the idea being to make the method return only +
symbols instead of user-input chars.
So for example if input is 123
, I expect +++
to be stored in variable s
.
And that does not work. Console hangs as if it is waiting more input. Only a certain amount of keypressing (or sending EOF) helps.
What am I missing here?
As was pointed out by @ferosekhanj, the problem was the missing newline, which was not returned by the modified version of underflow
to the caller. So in order for the code to work properly it has to be returned. This version of the method works fine.
virtual std::streambuf::int_type underflow()
{
std::streambuf::int_type result = buffer->sbumpc();
if ((result != traits_type::eof()) && !traits_type::eq(traits_type::to_char_type(result), '\n'))
{
result = traits_type::to_int_type('+');
ch = traits_type::to_char_type(result);
setg(&ch, &ch, &ch + 1);
}
return result;
}