readsome() on cin

The readsome() unformatted I/P function applied to cin doesn't seem to work properly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>         /// cin, cout
 
using namespace std;
 
 
void read()
{
    char buf[80] {};
 
    cin.readsome(buf, 3);
 
    if (cin)
    {
        cout << "cin.readsome() successfully read "
             << cin.gcount() << " characters: ";
 
        cout << buf << endl;
 
        cout << "next char: " << (char) cin.peek()
             << endl;
 
        /// discard the character
        cin.ignore();
    }
    else
        cout << "cin.readsome() was unsuccessful" << endl;
}
 
 
int main()
{
	for (int i = 0; i < 3; i++)
       read();
}


https://ideone.com/1XC8YT


Standard I/P:


1234567890



Standard O/P:


cin.readsome() successfully read 0 characters: 
next char: 1
cin.readsome() successfully read 0 characters: 
next char: 2
cin.readsome() successfully read 0 characters: 
next char: 3


My queries:
1) readsome()'s functionality is highly implementation-dependent (according to documentation). Is this the way readsome() is supposed to work with cin or am I doing something wrong?

Thanks
Last edited on
> Is this the way readsome() is supposed to work with cin or am I doing something wrong?

By default, input from std::cin is unbuffered (it needs to coexist peacefully with C stdio).
readsome() requires buffered input.

Make it buffered by doing this right at the outset:
1
2
// http://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio
std::ios_base::sync_with_stdio(false); // de-link C++ streams from their C counterparts 

and there is a reasonable chance that readsome() would work as expected by this program.
https://ideone.com/AMXKgK
Registered users can post here. Sign in or register to post.