zuroslav
zuroslav

Reputation: 337

How to read number of characters stored in input stream buffer

I have a quick question - how can I possibly write something in console window to std::cin without assigning it to a string or char[]? And then how to read the number of characters that are stored in buffer?

Let's say that I want to create an array of char, but it shall has the size of the input length. I might create a buffer or a variable of big size to store the input and then read its length, allocate memory to my char array and copy it. But let's also say that I am a purist and I don't want any additional (other than stream buffer) memory used. Is there a possibility to access std::cin buffer, read the number of characters stored and copy them to my array? I was trying to find the answer for several hours, reading cpp reference but I really couldn't find solution. I couldn't even find if there is a possibility to write something to std::cin buffer without assigning it to a variable, aka executing cin >> variable. I would appreciate any help, also if you have alternative solutions for this problem.

Also, does somebody know where can I find information about how buffers work (means where computer stores input from keyboard, how it is processed and how iostream works with computer to extract data from this).

Many thanks!

Upvotes: 2

Views: 3874

Answers (1)

Biruk Abebe
Biruk Abebe

Reputation: 2233

First of all in order for the input buffer to be filled you need to do some sort of read operation. The read operation may not necessary put what is read in to a variable. For example, cin.peek() may block until the user enters some value and returns the next character that will be read from the buffer without extracting it or you could also use cin.get along with cin.putback.

You can then use the streambuf::in_avail function to determine how many characters are in the input buffer including a new line character.

With that in mind you could do something like this:

char ch;
cin.get(ch);//this will block until some data is entered
cin.putback(ch);//put back the character read in the previous operation
streamsize size=cin.rdbuf()->in_avail();//get the number of character in the buffer available for reading(including spaces and new line)
if(size>0)
{
    char* arr=new char[size];//allocate the size of the array(you might want to add one more space for null terminator character)

   for(streamsize i=0;i<size;i++)
        cin.get(arr[i]);//copy each character, including spaces and newline, from the input buffer to the array

   for(streamsize i=0;i<size;i++)
        cout<<arr[i];//display the result
}

That being said, i am sure you have a specific reason for doing this, but i don't think it is a good idea to do I/O like this. If you don't want to estimate the size of the character array you need for input then you can always use a std::string and read the input instead.

Upvotes: 2

Related Questions